﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Xml;
using System.IO;
using System.Diagnostics;
using System.Globalization;
using PrintDataGrid;
using System.Configuration;
using System.Threading;

namespace SalariesApp
{
    public partial class Form1 : Form
    {
        #region Constants
        private const double PFAmount = 120;
        private const double ESIAmount = 120;
        #endregion

        #region Class Variables
        private bool IsLoggedIn = false;
        private DataTable Branches = null;
        private DataTable Departments = null;
        private DataTable Designations = null;
        private DataTable Employees = null;
        private string empID;
        private DateTime salaryDate;
        private int UserAction;

        private string BillAmtMain;
        private string AllowanceAmtMain;
        private string BalanceAmtMain;

        private string FinalSalaryMain;
        private DataTable ValidateLeaves = null;
        private DataTable ValidateOTs = null;
        private DataTable ValidateAdvance = null;
        private DataTable tempLeaves = null;
        private DataTable tempOTs = null;
        private DataTable tempAdvance = null;
        #endregion

        #region .Ctr
        public Form1()
        {
            InitializeComponent();

            try
            {
                Thread.CurrentThread.CurrentCulture = new CultureInfo("en-IN");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            //Setting TimeLines to Operate the Application
            //DateTime currentDate = GetCurrentDateTime();

            //June To Aug
            //if (!(currentDate.Month >= 5 && currentDate.Month <= 7))
            //{
            //    MessageBox.Show("Invalid Application Request!!! Contact Administrator.", "Invalid Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    this.Close();
            //    return;
            //}

            //Disabling the Tab Control Headers
            tabControl1.Appearance = TabAppearance.FlatButtons;
            tabControl1.ItemSize = new Size(0, 1);
            tabControl1.SizeMode = TabSizeMode.Fixed;

            tabControl2.Appearance = TabAppearance.FlatButtons;
            tabControl2.ItemSize = new Size(0, 1);
            tabControl2.SizeMode = TabSizeMode.Fixed;
        }
        #endregion

        #region Private Methods

        private DateTime GetCurrentDateTime()
        {
            try
            {
                WebRequest request = WebRequest.Create(@"http://developer.yahooapis.com/TimeService/V1/getTime?appid=Test");
                // request.Proxy = new WebProxy("PROXYSERVERNAME", 8080); // You may or may not need this 
                WebResponse response = request.GetResponse();

                Double currentTimeStamp = 0;
                using (Stream stream = response.GetResponseStream())
                {
                    using (XmlTextReader xmlReader = new XmlTextReader(stream))
                    {
                        while (xmlReader.Read())
                        {
                            switch (xmlReader.NodeType)
                            {
                                case XmlNodeType.Element:
                                    if (xmlReader.Name == "Timestamp")
                                    {
                                        currentTimeStamp = Convert.ToDouble(xmlReader.ReadInnerXml());
                                    }
                                    break;
                            }
                        }

                        xmlReader.Close();
                    }
                }

                DateTime yahooDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
                return yahooDateTime.AddSeconds(currentTimeStamp).AddHours(5).AddMinutes(30);
            }
            catch (Exception ex)
            {
                WriteToEventViewer("Couldn't get the current time from internet. " + ex.Message);
                return DateTime.Now;
            }
        }

        private void WriteToEventViewer(string message)
        {
            try
            {
                if (!EventLog.SourceExists("KSBakery"))
                    EventLog.CreateEventSource("KSBakery", "KSBakery");
                EventLog.WriteEntry("KSBakery", message, EventLogEntryType.Error);
            }
            catch (Exception)
            { }
        }

        private void ClearSearchFields()
        {
            try
            {
                rbNameSearch.Checked = true;
                rbBranchDeptSearch.Checked = false;
                txtNameSearch.Clear();
                txtNameSearch.Enabled = true;
                cmbBranchSearch.Enabled = false;
                //cmbDeptSearch.Enabled = false; 
                cmbSelectedEmployee.DataSource = null;
                cmbSelectedEmployee.Enabled = false;
                lblDeptInfo.Text = string.Empty;
                lblDesignation.Text = string.Empty;
                lblBranchInfo.Text = string.Empty;
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void ClearSalaryTabFields()
        {
            try
            {
                lblSalaryData.Text = string.Empty;
                lblAdvanceAmtData.Text = string.Empty;
                lblOTAmtData.Text = string.Empty;
                lblBillAmtData.Text = string.Empty;
                lblLeavesAmtData.Text = string.Empty;
                lblJoiningDateText.Text = "Joining Date:";
                txtLoanAmtData.Clear();
                txtExtraAmount.Clear();
                txtExtraAmtReason.Clear();
                lblSanctionedAmtData.Text = string.Empty;
                lblBalanceAmtData.Text = string.Empty;
                cmbMonth.DataSource = null;
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnPaySalary_Click(object sender, EventArgs e)
        {
            try
            {
                btnPaySalaryData.Enabled = false;
                btnValidateLeaves.Enabled = false;
                btnValidateOT.Enabled = false;
                btnValidateAdvance.Enabled = false;
                UserAction = (int)UserActionType.PaySalaryClick;
                //ClearSearchFields();
                ClearSalaryTabFields();

                cmbMonth.DataSource = GetMonthYears();
                cmbMonth.DisplayMember = "MonthYear";
                cmbMonth.ValueMember = "DateTime";
                DisplayNameSearchFields();
                tabControl2.SelectTab(1);
                btnSelectedEmployees_Click(sender, e);
                //btnSelectedEmployees_Click(sender, e);
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private List<DateTime> GetMaxandMinDates()
        {
            try
            {
                List<DateTime> dates = new List<DateTime>();
                if (DateTime.Now.Day > 10)
                {
                    //Max Date
                    dates.Add(new DateTime(DateTime.Now.AddMonths(1).Year, DateTime.Now.AddMonths(1).Month, 10));
                    dates.Add(new DateTime(DateTime.Now.Year, DateTime.Now.Month, 11));
                }
                else
                {
                    dates.Add(new DateTime(DateTime.Now.Year, DateTime.Now.Month, 10));
                    dates.Add(new DateTime(DateTime.Now.AddMonths(-1).Year, DateTime.Now.AddMonths(-1).Month, 11));
                }
                return dates;
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }

        private void btnPayAdvance_Click(object sender, EventArgs e)
        {
            try
            {
                if (cmbSelectedEmployee == null || cmbSelectedEmployee.SelectedValue == null)
                {
                    MessageBox.Show("Please select the employee to proceed further.", "Select Employee", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                lblAlreadyAdvanceAmount.Text = "-";
                txtAdvAmt.Clear();
                dtAdvanceTaken.ResetText();
                btnFinalPayAdvance.Enabled = false;
                List<DateTime> maxAndMinDates = GetMaxandMinDates();
                dtAdvanceTaken.MaxDate = maxAndMinDates[0];
                dtAdvanceTaken.MinDate = maxAndMinDates[1];
                UserAction = (int)UserActionType.PayAdvanceClick;
                lblSalaryAdvance.Text = string.Empty;
                lblAlreadyAdvanceAmount.Text = string.Empty;
                txtAdvAmt.Clear();
                tabControl2.SelectTab(2);
                DisplayNameSearchFields();

                lblAdvanceDetailsHeader.Text = "Advance Details for " + cmbSelectedEmployee.Text;
                empID = cmbSelectedEmployee.SelectedValue.ToString();
                if (Employees == null)
                    Employees = DBHelper.FetchEmployeesByName(string.Empty, true);
                lblSalaryAdvance.Text = Employees.Select(string.Format("EmpID = {0}", empID))[0]["Salary"].ToString();
                DataTable dsAdvance = DBHelper.FetchCurrentMonthAdvanceDetails(empID);
                double adv = 0d;
                if (dsAdvance != null && dsAdvance.Rows.Count > 0)
                    foreach (DataRow dr in dsAdvance.Rows)
                        adv += double.Parse(dr["Amount"].ToString());
                lblAlreadyAdvanceAmount.Text = adv.ToString();
                if (lblAlreadyAdvanceAmount.Text.Trim() == string.Empty)
                    lblAlreadyAdvanceAmount.Text = "-";
                btnFinalPayAdvance.Enabled = true;


                /*lblAlreadyAdvanceAmount.Text = "-";
                txtAdvAmt.Clear();
                dtAdvanceTaken.ResetText();

                btnFinalPayAdvance.Enabled = true;
                if (cmbSelectedEmployee == null || cmbSelectedEmployee.SelectedValue == null)
                {
                    MessageBox.Show("Please select the employee to proceed further.", "Select Employee", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                lblAdvanceDetailsHeader.Text = "Advance Details for " + cmbSelectedEmployee.Text;
                empID = cmbSelectedEmployee.SelectedValue.ToString();
                lblSalaryAdvance.Text = Employees.Select(string.Format("EmpID = {0}", empID))[0]["Salary"].ToString();
                //DataTable dsAdvance = DBHelper.FetchCurrentMonthAdvanceDetails(empID);
                if (dsAdvance != null && dsAdvance.Rows.Count > 0)
                    lblAlreadyAdvanceAmount.Text = dsAdvance.Rows[0]["AdvanceAmt"].ToString();
                if (lblAlreadyAdvanceAmount.Text.Trim() == string.Empty)
                    lblAlreadyAdvanceAmount.Text = "-";*/
                txtAdvAmt.Focus();
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSelectedEmployees_Click(object sender, EventArgs e)
        {
            try
            {
                txtReducedAllowanceAmt.Enabled = false;
                lblLeftIcon.Visible = false;
                btnPaySalaryData.Enabled = true;
                btnValidateLeaves.Enabled = true;
                btnValidateAdvance.Enabled = true;
                btnValidateOT.Enabled = true;
                //lblSanctionedAmtData.Text = string.Empty;
                //lblBalanceAmtData.Text = string.Empty;
                if (cmbSelectedEmployee == null || cmbSelectedEmployee.SelectedValue == null)
                {
                    MessageBox.Show("Please select the employee to proceed further.", "Select Employee", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                empID = cmbSelectedEmployee.SelectedValue.ToString();
                salaryDate = DateTime.Parse(cmbMonth.SelectedValue.ToString());
                if (Employees == null)
                    Employees = DBHelper.FetchEmployeesByName(string.Empty, true);
                lblJoiningDateText.Text = "Joining Date: " + Employees.Select(string.Format("EmpID = {0}", empID))[0]["JoiningDate"].ToString();
                lbl10DaysSal.Text = Employees.Select(string.Format("EmpID = {0}", empID))[0]["TenDaysSalary"].ToString();
                DataTable dtChecker = DBHelper.CheckWhetherSalaryPaid(empID, salaryDate);
                txtLoanAmtData.Clear();
                txtExtraAmount.Clear();
                txtExtraAmtReason.Clear();
                txtReduceBillAmt.Clear();
                txtReducedAllowanceAmt.Clear();
                BillsTab.SelectTab(0);
                string str = "Salary details of " + cmbSelectedEmployee.Text + " for " + cmbMonth.Text;
                lblSalaryDetailsHeader.Text = str.Replace("\n", string.Empty);
                if (dtChecker != null && dtChecker.Rows.Count > 0)
                {
                    lblSalaryPaidIcon.Visible = true;
                    txtLoanAmtData.Enabled = false;
                    txtExtraAmount.Enabled = false;
                    txtExtraAmtReason.Enabled = false;
                    txtReduceBillAmt.Enabled = false;
                    btnPaySalaryData.Enabled = false;
                    btnValidateLeaves.Enabled = false;
                    btnValidateOT.Enabled = false;
                    btnValidateAdvance.Enabled = false;
                    txtReduceBillAmt.Enabled = false;
                    FillPaidSalaryDetails(dtChecker);
                    btnCalculate.Enabled = false;
                }
                else
                {
                    lblSalaryPaidIcon.Visible = false;
                    txtLoanAmtData.Enabled = true;
                    txtExtraAmount.Enabled = true;
                    txtExtraAmtReason.Enabled = true;
                    btnPaySalaryData.Enabled = true;
                    btnValidateLeaves.Enabled = true;
                    btnValidateOT.Enabled = true;
                    btnValidateAdvance.Enabled = true;
                    FillUnPaidSalaryDetailsLatest();
                    txtReduceBillAmt.Enabled = !(lblBillAmtData.Text == string.Empty || lblBillAmtData.Text == "0");
                    btnCalculate.Enabled = true;
                }
                //dgAdvanceDetailsData.Columns[0].Width = 90;
                //dgAdvanceDetailsData.Columns[1].Width = 90;

                //dgLeavesDetailsData.Columns[0].Width = 40;
                //dgLeavesDetailsData.Columns[0].HeaderText = "ID";
                //dgLeavesDetailsData.Columns[2].Width = 85;
                //dgLeavesDetailsData.Columns[3].Width = 70;

                //dgOTDetailsData.Columns[0].Width = 40;
                //dgOTDetailsData.Columns[0].HeaderText = "ID";
                //dgOTDetailsData.Columns[2].Width = 85;
                //dgOTDetailsData.Columns[3].Width = 70;

                dgBillDetailsData.Columns[2].Width = 85;
                dgBillDetailsData.Columns[3].Width = 90;
                btnPaySalaryData.Enabled = false;
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void FillPaidSalaryDetails(DataTable dtSalaryDetails)
        {
            try
            {
                lblSalaryData.Text = dtSalaryDetails.Rows[0]["SalaryAmount"].ToString();
                lblAdvanceAmtData.Text = dtSalaryDetails.Rows[0]["AdvanceAmount"].ToString();
                lblLeavesAmtData.Text = dtSalaryDetails.Rows[0]["LeavesAmount"].ToString();
                lblOTAmtData.Text = dtSalaryDetails.Rows[0]["OTAmount"].ToString();
                lblBillAmtData.Text = BillAmtMain = dtSalaryDetails.Rows[0]["BillsAmount"].ToString();
                txtLoanAmtData.Text = dtSalaryDetails.Rows[0]["LoanAmount"].ToString();
                lblFinalSalaryData.Text = FinalSalaryMain = dtSalaryDetails.Rows[0]["FinalSalaryAmount"].ToString();
                lblPFAmtData.Text = dtSalaryDetails.Rows[0]["PFAmount"].ToString();
                txtReduceBillAmt.Text = dtSalaryDetails.Rows[0]["DeductedBillAmount"].ToString();
                lblLeavesCount.Tag = dtSalaryDetails.Rows[0]["LeaveDays"].ToString();
                lblLeavesCount.Text = "(" + lblLeavesCount.Tag.ToString() + " Days)";
                lblOTCount.Tag = dtSalaryDetails.Rows[0]["OTDays"].ToString();
                lblOTCount.Text = "(" + lblOTCount.Tag.ToString() + " Days)";
                lblAllowance.Text = dtSalaryDetails.Rows[0]["Allowance"].ToString();
                txtReducedAllowanceAmt.Text = dtSalaryDetails.Rows[0]["DeductedAllowance"].ToString();

                txtExtraAmount.Text = dtSalaryDetails.Rows[0]["ExtraAmount"].ToString();
                txtExtraAmtReason.Text = dtSalaryDetails.Rows[0]["Reason"].ToString();

                DataSet dsDetails = DBHelper.FetchTransactionDetailsForPaid(empID, salaryDate);
                //Advances
                dgAdvanceDetailsData.DataSource = dsDetails.Tables[0];
                dgAdvanceDetailsData.Columns[0].Visible = false;
                dgAdvanceDetailsData.Columns[1].Visible = false;

                //Leaves
                dgLeavesDetailsData.DataSource = dsDetails.Tables[1];
                dgLeavesDetailsData.Columns[0].Width = 40;
                dgLeavesDetailsData.Columns[1].Visible = false;
                dgLeavesDetailsData.Columns[2].Width = 90;
                dgLeavesDetailsData.Columns[3].Width = 60;

                //OT's
                dgOTDetailsData.DataSource = dsDetails.Tables[2];
                dgOTDetailsData.Columns[0].HeaderText = "ID";
                dgOTDetailsData.Columns[0].Width = 40;
                dgOTDetailsData.Columns[1].Visible = false;
                dgOTDetailsData.Columns[2].Width = 90;
                dgOTDetailsData.Columns[3].Width = 60;

                //Bills
                dgBillDetailsData.DataSource = dsDetails.Tables[3];
                dgBillDetailsData.Columns[0].Visible = false;
                dgBillDetailsData.Columns[1].Visible = false;

                lblSanctionedAmtData.Text = dtSalaryDetails.Rows[0]["SanctionedAmt"].ToString();
                lblBalanceAmtData.Text = dtSalaryDetails.Rows[0]["BalanceAmt"].ToString();

                //LoanIssuedAmount
                /*double sanctionedAmt = 0;
                if(dsDetails.Tables.Count > 4 && dsDetails.Tables[4].Rows.Count > 0)
                    foreach (DataRow row in dsDetails.Tables[4].Rows)
                    {
                        sanctionedAmt = double.Parse(dsDetails.Tables[4].Rows[0]["IssuedAmount"].ToString());
                        lblSanctionedAmtData.Text = dsDetails.Tables[4].Rows[0]["IssuedAmount"].ToString();
                    }

                //Repayed Amount
                if (dsDetails.Tables.Count > 5 && dsDetails.Tables[5].Rows.Count > 0)
                    foreach (DataRow row in dsDetails.Tables[5].Rows)
                    {
                        double repayedAmt = double.Parse(dsDetails.Tables[5].Rows[0]["RepayedAmt"].ToString());
                        lblBalanceAmtData.Text = (sanctionedAmt - repayedAmt).ToString();
                    }*/
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void FillUnPaidSalaryDetailsLatest()
        {
            try
            {
                DataSet dsDetails = DBHelper.FetchTransactionDetailsForUnPaid(empID, salaryDate);

                double salary = 0;
                double advanceAmt = 0;
                double leavesAmt = 0;
                double otAmt = 0;
                double billAmt = 0;

                DateTime joiningDate = DateTime.Parse(dsDetails.Tables[4].Rows[0]["JoiningDate"].ToString());
                int noofDays = 0;

                if ((salaryDate.AddMonths(-1).Year < joiningDate.Year) || (salaryDate.AddMonths(-1).Year == joiningDate.Year && salaryDate.AddMonths(-1).Month < joiningDate.Month))
                {
                    MessageBox.Show("Salary Invalid at this time for this employee", "Invalid Time", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    tabControl2.SelectTab(0);
                    return;
                }
                else if (salaryDate.AddMonths(-1).Month == joiningDate.Month && salaryDate.AddMonths(-1).Year == joiningDate.Year)
                {
                    //10 days salary will be on hold
                    //If employee joined in last month then eligible for (salaryDays - 10) days of salary
                    noofDays = salaryDate.AddDays(-1).Day - joiningDate.Day + 1;
                    double actualsalary = double.Parse(dsDetails.Tables[4].Rows[0]["Salary"].ToString());
                    salary = Math.Round(noofDays * actualsalary / 30, 2);
                }
                else
                {
                    salary = double.Parse(dsDetails.Tables[4].Rows[0]["Salary"].ToString());
                }

                //NEW CODE
                tempAdvance = new DataTable();
                tempAdvance = dsDetails.Tables[0].Clone();

                ValidateAdvance = new DataTable();
                ValidateAdvance = dsDetails.Tables[0].Clone();

                foreach (DataRow row in dsDetails.Tables[0].Rows)
                {
                    if (Convert.ToBoolean(row["Valid"]))
                        tempAdvance.ImportRow(row);
                    ValidateAdvance.ImportRow(row);
                }

                //Advances
                dgAdvanceDetailsData.DataSource = dsDetails.Tables[0];
                dgAdvanceDetailsData.Columns[0].Width = 40;
                dgAdvanceDetailsData.Columns[1].Visible = false;
                dgAdvanceDetailsData.Columns[2].Visible = false;
                dgAdvanceDetailsData.Columns[3].Width = 90;
                dgAdvanceDetailsData.Columns[4].Width = 70;
                dgAdvanceDetailsData.Columns[5].Visible = false;

                foreach (DataRow row in dsDetails.Tables[0].Rows)
                {
                    advanceAmt += double.Parse(row["Amount"].ToString());
                }

                bool leavesCounted = bool.Parse(dsDetails.Tables[4].Rows[0]["IsLeavesConsidered"].ToString());

                //Leaves
                tempLeaves = new DataTable();
                tempLeaves = dsDetails.Tables[1].Clone();

                ValidateLeaves = new DataTable();
                ValidateLeaves = dsDetails.Tables[1].Clone();

                foreach (DataRow row in dsDetails.Tables[1].Rows)
                {
                    if (Convert.ToBoolean(row["Valid"]))
                        tempLeaves.ImportRow(row);
                    ValidateLeaves.ImportRow(row);
                }

                dgLeavesDetailsData.DataSource = null;
                dgLeavesDetailsData.DataSource = tempLeaves;
                dgLeavesDetailsData.Columns[0].Width = 40;
                dgLeavesDetailsData.Columns[3].Width = 90;
                dgLeavesDetailsData.Columns[4].Width = 70;
                dgLeavesDetailsData.Columns[5].Visible = false;
                dgLeavesDetailsData.Columns[1].Visible = false;
                dgLeavesDetailsData.Columns[2].Visible = false;
                //foreach (DataRow row in dsDetails.Tables[1].Rows)
                //    ValidateLeaves.ImportRow(row);

                double counted = 0;
                if (noofDays == 0 || (noofDays != 0 && joiningDate.Day < 10))
                {
                    //Calculate # of Leaves
                    foreach (DataGridViewRow row in dgLeavesDetailsData.Rows)
                    {
                        if (bool.Parse(row.Cells["Half Day"].Value.ToString()))
                        {
                            counted += 0.5;
                        }
                        else
                        {
                            counted += 1;
                        }
                    }
                    double leavesUnCnt = 0d;
                    if (leavesCounted)
                    {
                        if (counted < 8)
                        {
                            leavesUnCnt = 4.0 - counted;
                        }
                        else
                        {
                            leavesUnCnt = -counted;
                        }
                    }
                    else
                    {
                        leavesUnCnt = -counted;
                    }

                    leavesAmt = Math.Round(leavesUnCnt * (salary / 30), 2);
                    //leavesCount = leavesUnCnt;
                    lblLeavesCount.Text = "(" + leavesUnCnt.ToString() + " Days)";
                    lblLeavesCount.Tag = leavesUnCnt;
                }
                else
                {
                    leavesAmt = 0;
                    lblLeavesCount.Text = "(0 Days)";
                    lblLeavesCount.Tag = 0;
                }

                //OT's
                tempOTs = new DataTable();
                tempOTs = dsDetails.Tables[2].Clone();

                ValidateOTs = new DataTable();
                ValidateOTs = dsDetails.Tables[2].Clone();

                foreach (DataRow row in dsDetails.Tables[2].Rows)
                {
                    if (Convert.ToBoolean(row["Valid"]))
                        tempOTs.ImportRow(row);
                    ValidateOTs.ImportRow(row);
                }

                dgOTDetailsData.DataSource = null;
                dgOTDetailsData.DataSource = tempOTs;
                dgOTDetailsData.Columns[0].Width = 40;
                dgOTDetailsData.Columns[1].Visible = false;
                dgOTDetailsData.Columns[2].Visible = false;
                dgOTDetailsData.Columns[3].Width = 90;
                dgOTDetailsData.Columns[4].Width = 70;
                dgOTDetailsData.Columns[5].Visible = false;
                counted = 0;

                foreach (DataGridViewRow row in dgOTDetailsData.Rows)
                {
                    if (bool.Parse(row.Cells["Half Day"].Value.ToString()))
                        counted += 0.5;
                    else
                        counted += 1;
                }
                otAmt = counted * (salary / 30);
                //otCount = counted;
                lblOTCount.Text = "(" + counted.ToString() + " Days)";
                lblOTCount.Tag = counted;

                //Considering 15% extra pay for OT
                otAmt = Math.Round(1.15 * otAmt, 2);

                //Bills
                dgBillDetailsData.DataSource = dsDetails.Tables[3];
                dgBillDetailsData.Columns[0].Visible = false;
                dgBillDetailsData.Columns[1].Visible = false;
                foreach (DataRow row in dsDetails.Tables[3].Rows)
                {
                    billAmt += double.Parse(row["Amount"].ToString());
                }

                txtBillAmt.Text = BillAmtMain = billAmt.ToString();
                if (lblBillAmtData.Text != "0")
                {
                    txtReduceBillAmt.Enabled = true;
                    txtReduceBillAmt.Text = (billAmt * 0.25).ToString();
                    txtReduceBillAmt_KeyUp(null, null);
                }

                double pfAmt = 0;
                //double esiAmt = 0;
                if (dsDetails.Tables.Count > 4 && dsDetails.Tables[4].Rows.Count > 0)
                {
                    if (bool.Parse(dsDetails.Tables[4].Rows[0]["IsPFIncluded"].ToString()))
                    {
                        double.TryParse(dsDetails.Tables[4].Rows[0]["PFAmount"].ToString(), out pfAmt);
                        lblPFAmtData.Text = pfAmt.ToString();
                    }
                    else
                    {
                        pfAmt = 0;
                        lblPFAmtData.Text = string.Empty;
                    }

                    lblPF.Text = pfAmt.ToString();

                    if (bool.Parse(dsDetails.Tables[4].Rows[0]["IsLeft"].ToString()))
                    {
                        lblLeftIcon.Visible = true;
                        txtLoanAmtData.Enabled = false;
                        txtExtraAmount.Enabled = false;
                        txtExtraAmtReason.Enabled = false;
                        txtReduceBillAmt.Enabled = false;
                        btnPaySalaryData.Enabled = false;
                        btnValidateLeaves.Enabled = false;
                        btnValidateOT.Enabled = false;
                        btnValidateAdvance.Enabled = false;
                    }

                    lblAllowance.Text = AllowanceAmtMain = dsDetails.Tables[4].Rows[0]["Allowance"].ToString();
                    double allowanceDeduct = 0d;
                    if (double.TryParse(lblAllowance.Text, out allowanceDeduct))
                    {
                        if (allowanceDeduct > 0)
                        {
                            txtReducedAllowanceAmt.Enabled = true;
                        }
                    }
                }

                //Loan Details
                double sanctionedAmt = 0;
                if (dsDetails.Tables.Count > 5 && dsDetails.Tables[5].Rows.Count > 0)
                {
                    foreach (DataRow row in dsDetails.Tables[5].Rows)
                    {
                        sanctionedAmt += double.Parse(row["IssuedAmount"].ToString());
                    }

                    //loanID = dsDetails.Tables[5].Rows[0]["LoanID"].ToString();
                    //lblLoanIDData.Text = dsDetails.Tables[5].Rows[0]["LoanID"].ToString();
                    //sanctionedAmt = double.Parse(dsDetails.Tables[5].Rows[0]["IssuedAmount"].ToString());
                    lblSanctionedAmtData.Text = sanctionedAmt.ToString();
                    txtLoanAmtData.Enabled = true;
                }
                else
                {
                    //loanID = string.Empty;
                    //lblLoanIDData.Text = string.Empty;
                    lblSanctionedAmtData.Text = string.Empty;
                    txtLoanAmtData.Enabled = false;
                }

                if (dsDetails.Tables.Count > 6 && dsDetails.Tables[6].Rows.Count > 0 && dsDetails.Tables[6].Rows[0]["RepayedAmt"].ToString() != string.Empty)
                {
                    double repayedAmt = double.Parse(dsDetails.Tables[6].Rows[0]["RepayedAmt"].ToString());
                    lblBalanceAmtData.Text = BalanceAmtMain = (sanctionedAmt - repayedAmt).ToString();
                }
                else
                {
                    if (sanctionedAmt != 0)
                    {
                        lblBalanceAmtData.Text = BalanceAmtMain = sanctionedAmt.ToString();
                    }
                    else
                    {
                        lblBalanceAmtData.Text = BalanceAmtMain = string.Empty;
                    }
                }

                //Latest Logic
                if (dsDetails.Tables.Count > 3 && dsDetails.Tables[4].Rows.Count > 0)
                {
                    lblSalaryData.Text = salary.ToString();
                    lblAdvanceAmtData.Text = advanceAmt.ToString();
                    lblLeavesAmtData.Text = leavesAmt.ToString();
                    lblOTAmtData.Text = otAmt.ToString();

                    //Calculate Final Set of Details
                    CalculateLatest();
                }














                /*//Salary Details
                if (dsDetails.Tables.Count > 3 && dsDetails.Tables[4].Rows.Count > 0)
                {
                    double allowanceDeduct = 0d;

                    lblSalaryData.Text = salary.ToString();
                    lblAdvanceAmtData.Text = advanceAmt.ToString();
                    lblLeavesAmtData.Text = leavesAmt.ToString();
                    lblOTAmtData.Text = otAmt.ToString();
                    lblBillAmtData.Text = BillAmtMain = billAmt.ToString();
                    if (lblBillAmtData.Text != "0")
                    {
                        txtReduceBillAmt.Enabled = true;
                        txtReduceBillAmt.Text = (billAmt * 0.25).ToString();
                        allowanceDeduct = billAmt * 0.25;
                        txtReduceBillAmt_KeyUp(null, null);
                    }
                    if (!double.TryParse(txtLoanAmtData.Text == string.Empty ? "0" : txtLoanAmtData.Text, out loanAmt))
                    {
                        MessageBox.Show("Enter Valid Amount in Loan Amount field", "Invalid Loan Amount", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txtLoanAmtData.Text = string.Empty;
                        return;
                    }

                    //lblFinalSalaryData.Text = FinalSalaryMain = (Math.Ceiling(salary - advanceAmt + leavesAmt + otAmt - loanAmt - billAmt - pfAmt - esiAmt + double.Parse(lblAllowance.Text) + allowanceDeduct)).ToString();
                    lblFinalSalaryData.Text = FinalSalaryMain = (Math.Ceiling(salary - advanceAmt + leavesAmt + otAmt - loanAmt - billAmt - pfAmt - esiAmt + double.Parse(lblAllowance.Text) + allowanceDeduct)).ToString();
                    FinalSalaryWithOutBillsMain = (Math.Ceiling(salary - advanceAmt + leavesAmt + otAmt - loanAmt - pfAmt - esiAmt + double.Parse(lblAllowance.Text))).ToString();
                    SanctLoanAmt = sanctionedAmt;
                    double temp = 0d;
                    if (double.TryParse(lblBalanceAmtData.Text, out temp))
                        BalLoanAmt = temp;
                    else
                        BalLoanAmt = 0d;
                }*/
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void CalculateLatest()
        {
            //Get All Details
            double salary = 0d;
            double advance = 0d;
            double leaves = 0d;
            double ot = 0d;
            double bills = 0d;
            double pf = 0d;
            double allowance = 0d;
            double loan = 0d;
            double extra = 0d;

            double.TryParse(lblSalaryData.Text, out salary);
            double.TryParse(lblAdvanceAmtData.Text, out advance);
            double.TryParse(lblLeavesAmtData.Text, out leaves);
            double.TryParse(lblOTAmtData.Text, out ot);
            double.TryParse(lblBillAmtData.Text, out bills);
            double.TryParse(lblPFAmtData.Text, out pf);
            double.TryParse(lblAllowance.Text, out allowance);
            double.TryParse(txtLoanAmtData.Text, out loan);
            double.TryParse(txtExtraAmount.Text, out extra);

            lblFinalSalaryData.Text = (Math.Ceiling(salary - advance + leaves + ot - bills - pf + allowance - loan + extra)).ToString();

            double balanceLoanAmt = 0d;
            double.TryParse(BalanceAmtMain, out balanceLoanAmt);

            lblBalanceAmtData.Text = (balanceLoanAmt - loan).ToString();
        }

        double SanctLoanAmt = 0d;
        double CurrentPaidAmt = 0d;

        //private void FillUnPaidSalaryDetails()
        //{
        //    try
        //    {
        //        DataSet dsDetails = DBHelper.FetchTransactionDetailsForUnPaid(empID, salaryDate);

        //        double salary = 0;
        //        double advanceAmt = 0;
        //        double leavesAmt = 0;
        //        double otAmt = 0;
        //        double billAmt = 0;
        //        double loanAmt = 0;

        //        DateTime joiningDate = DateTime.Parse(dsDetails.Tables[4].Rows[0]["JoiningDate"].ToString());
        //        if (salaryDate.AddMonths(-1).Month == joiningDate.Month && salaryDate.AddMonths(-1).Year == joiningDate.Year)
        //        {
        //            int noofDays = 30 - joiningDate.Day + 1;
        //            double actualsalary = double.Parse(dsDetails.Tables[4].Rows[0]["Salary"].ToString());
        //            salary = Math.Round(noofDays * actualsalary / 30, 2);
        //        }
        //        else if ((salaryDate.AddMonths(-1).Year < joiningDate.Year) || (salaryDate.AddMonths(-1).Year == joiningDate.Year && salaryDate.AddMonths(-1).Month < joiningDate.Month))
        //        {
        //            MessageBox.Show("Salary Invalid at this time for this employee", "Invalid Time", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //            tabControl2.SelectTab(0);
        //            return;
        //        }
        //        else
        //        {
        //            salary = double.Parse(dsDetails.Tables[4].Rows[0]["Salary"].ToString());
        //        }

        //        //NEW CODE
        //        tempAdvance = new DataTable();
        //        tempAdvance = dsDetails.Tables[0].Clone();

        //        ValidateAdvance = new DataTable();
        //        ValidateAdvance = dsDetails.Tables[0].Clone();

        //        foreach (DataRow row in dsDetails.Tables[0].Rows)
        //        {
        //            if (Convert.ToBoolean(row["Valid"]))
        //                tempAdvance.ImportRow(row);
        //            ValidateAdvance.ImportRow(row);
        //        }

        //        //Advances
        //        dgAdvanceDetailsData.DataSource = dsDetails.Tables[0];
        //        dgAdvanceDetailsData.Columns[0].Width = 40;
        //        dgAdvanceDetailsData.Columns[1].Visible = false;
        //        dgAdvanceDetailsData.Columns[2].Visible = false;
        //        dgAdvanceDetailsData.Columns[3].Width = 90;
        //        dgAdvanceDetailsData.Columns[4].Width = 70;
        //        dgAdvanceDetailsData.Columns[5].Visible = false;

        //        foreach (DataRow row in dsDetails.Tables[0].Rows)
        //        {
        //            advanceAmt += double.Parse(row["Amount"].ToString());
        //        }

        //        bool leavesCounted = bool.Parse(dsDetails.Tables[4].Rows[0]["IsLeavesConsidered"].ToString());

        //        //Leaves
        //        tempLeaves = new DataTable();
        //        tempLeaves = dsDetails.Tables[1].Clone();

        //        ValidateLeaves = new DataTable();
        //        ValidateLeaves = dsDetails.Tables[1].Clone();

        //        foreach (DataRow row in dsDetails.Tables[1].Rows)
        //        {
        //            if (Convert.ToBoolean(row["Valid"]))
        //                tempLeaves.ImportRow(row);
        //            ValidateLeaves.ImportRow(row);
        //        }

        //        dgLeavesDetailsData.DataSource = null;
        //        dgLeavesDetailsData.DataSource = tempLeaves;
        //        dgLeavesDetailsData.Columns[0].Width = 40;
        //        dgLeavesDetailsData.Columns[3].Width = 90;
        //        dgLeavesDetailsData.Columns[4].Width = 70;
        //        dgLeavesDetailsData.Columns[5].Visible = false;
        //        dgLeavesDetailsData.Columns[1].Visible = false;
        //        dgLeavesDetailsData.Columns[2].Visible = false;
        //        //foreach (DataRow row in dsDetails.Tables[1].Rows)
        //        //    ValidateLeaves.ImportRow(row);

        //        //Calculate # of Leaves
        //        double counted = 0;
        //        foreach (DataGridViewRow row in dgLeavesDetailsData.Rows)
        //        {
        //            if (bool.Parse(row.Cells["Half Day"].Value.ToString()))
        //                counted += 0.5;
        //            else
        //                counted += 1;
        //        }
        //        double leavesUnCnt = 0d;
        //        if (leavesCounted)
        //        {
        //            if (counted < 8)
        //                leavesUnCnt = 4.0 - counted;
        //            else
        //                leavesUnCnt = -counted;
        //        }
        //        else
        //            leavesUnCnt = -counted;
        //        leavesAmt = Math.Round(leavesUnCnt * (salary / 30), 2);
        //        //leavesCount = leavesUnCnt;
        //        lblLeavesCount.Text = "(" + leavesUnCnt.ToString() + " Days)";
        //        lblLeavesCount.Tag = leavesUnCnt;

        //        //OT's
        //        tempOTs = new DataTable();
        //        tempOTs = dsDetails.Tables[2].Clone();

        //        ValidateOTs = new DataTable();
        //        ValidateOTs = dsDetails.Tables[2].Clone();

        //        foreach (DataRow row in dsDetails.Tables[2].Rows)
        //        {
        //            if (Convert.ToBoolean(row["Valid"]))
        //                tempOTs.ImportRow(row);
        //            ValidateOTs.ImportRow(row);
        //        }

        //        dgOTDetailsData.DataSource = null;
        //        dgOTDetailsData.DataSource = tempOTs;
        //        dgOTDetailsData.Columns[0].Width = 40;
        //        dgOTDetailsData.Columns[1].Visible = false;
        //        dgOTDetailsData.Columns[2].Visible = false;
        //        dgOTDetailsData.Columns[3].Width = 90;
        //        dgOTDetailsData.Columns[4].Width = 70;
        //        dgOTDetailsData.Columns[5].Visible = false;
        //        counted = 0;

        //        foreach (DataGridViewRow row in dgOTDetailsData.Rows)
        //        {
        //            if (bool.Parse(row.Cells["Half Day"].Value.ToString()))
        //                counted += 0.5;
        //            else
        //                counted += 1;
        //        }
        //        otAmt = counted * (salary / 30);
        //        //otCount = counted;
        //        lblOTCount.Text = "(" + counted.ToString() + " Days)";
        //        lblOTCount.Tag = counted;

        //        //Considering 15% extra pay for OT
        //        otAmt = Math.Round(1.15 * otAmt, 2);

        //        //Bills
        //        dgBillDetailsData.DataSource = dsDetails.Tables[3];
        //        dgBillDetailsData.Columns[0].Visible = false;
        //        dgBillDetailsData.Columns[1].Visible = false;
        //        foreach (DataRow row in dsDetails.Tables[3].Rows)
        //        {
        //            billAmt += double.Parse(row["Amount"].ToString());
        //        }

        //        double pfAmt = 0;
        //        double esiAmt = 0;
        //        if (dsDetails.Tables.Count > 4 && dsDetails.Tables[4].Rows.Count > 0)
        //        {
        //            if (bool.Parse(dsDetails.Tables[4].Rows[0]["IsPFIncluded"].ToString()))
        //            {
        //                double.TryParse(dsDetails.Tables[4].Rows[0]["PFAmount"].ToString(), out pfAmt);
        //                lblPFAmtData.Text = pfAmt.ToString();
        //            }
        //            else
        //            {
        //                pfAmt = 0;
        //                lblPFAmtData.Text = string.Empty;
        //            }

        //            lblPF.Text = pfAmt.ToString();

        //            if (bool.Parse(dsDetails.Tables[4].Rows[0]["IsLeft"].ToString()))
        //            {
        //                lblLeftIcon.Visible = true;
        //                txtLoanAmtData.Enabled = false;
        //                txtExtraAmount.Enabled = false;
        //                txtExtraAmtReason.Enabled = false;
        //                txtReduceBillAmt.Enabled = false;
        //                btnPaySalaryData.Enabled = false;
        //                btnValidateLeaves.Enabled = false;
        //                btnValidateOT.Enabled = false;
        //                btnValidateAdvance.Enabled = false;
        //            }

        //            lblAllowance.Text = AllowanceAmtMain = dsDetails.Tables[4].Rows[0]["Allowance"].ToString();
        //        }

        //        //Loan Details
        //        double sanctionedAmt = 0;
        //        if (dsDetails.Tables.Count > 5 && dsDetails.Tables[5].Rows.Count > 0)
        //        {
        //            loanID = dsDetails.Tables[5].Rows[0]["LoanID"].ToString();
        //            //lblLoanIDData.Text = dsDetails.Tables[5].Rows[0]["LoanID"].ToString();
        //            sanctionedAmt = double.Parse(dsDetails.Tables[5].Rows[0]["IssuedAmount"].ToString());
        //            lblSanctionedAmtData.Text = dsDetails.Tables[5].Rows[0]["IssuedAmount"].ToString();
        //            txtLoanAmtData.Enabled = true;
        //        }
        //        else
        //        {
        //            loanID = string.Empty;
        //            //lblLoanIDData.Text = string.Empty;
        //            lblSanctionedAmtData.Text = string.Empty;
        //            txtLoanAmtData.Enabled = false;
        //        }

        //        if (dsDetails.Tables.Count > 6 && dsDetails.Tables[6].Rows.Count > 0 && dsDetails.Tables[6].Rows[0]["RepayedAmt"].ToString() != string.Empty)
        //        {
        //            double repayedAmt = double.Parse(dsDetails.Tables[6].Rows[0]["RepayedAmt"].ToString());
        //            lblBalanceAmtData.Text = (sanctionedAmt - repayedAmt).ToString();
        //        }
        //        else
        //        {
        //            if (sanctionedAmt != 0)
        //            {
        //                lblBalanceAmtData.Text = sanctionedAmt.ToString();
        //            }
        //            else
        //            {
        //                lblBalanceAmtData.Text = string.Empty;
        //            }
        //        }

        //        double allowanceDeduct = 0d;

        //        if (double.TryParse(lblAllowance.Text, out allowanceDeduct))
        //        {
        //            if (allowanceDeduct > 0)
        //                txtReducedAllowanceAmt.Enabled = true;
        //        }

        //        double.TryParse(txtReducedAllowanceAmt.Text, out allowanceDeduct);

        //        //Salary Details
        //        if (dsDetails.Tables.Count > 3 && dsDetails.Tables[4].Rows.Count > 0)
        //        {
        //            lblSalaryData.Text = salary.ToString();
        //            lblAdvanceAmtData.Text = advanceAmt.ToString();
        //            lblLeavesAmtData.Text = leavesAmt.ToString();
        //            lblOTAmtData.Text = otAmt.ToString();
        //            lblBillAmtData.Text = BillAmtMain = billAmt.ToString();
        //            if (lblBillAmtData.Text != "0")
        //            {
        //                txtReduceBillAmt.Enabled = true;
        //                txtReduceBillAmt.Text = (billAmt * 0.25).ToString();
        //                allowanceDeduct = billAmt * 0.25;
        //                txtReduceBillAmt_KeyUp(null, null);
        //            }
        //            if (!double.TryParse(txtLoanAmtData.Text == string.Empty ? "0" : txtLoanAmtData.Text, out loanAmt))
        //            {
        //                MessageBox.Show("Enter Valid Amount in Loan Amount field", "Invalid Loan Amount", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //                txtLoanAmtData.Text = string.Empty;
        //                return;
        //            }

        //            //lblFinalSalaryData.Text = FinalSalaryMain = (Math.Ceiling(salary - advanceAmt + leavesAmt + otAmt - loanAmt - billAmt - pfAmt - esiAmt + double.Parse(lblAllowance.Text) + allowanceDeduct)).ToString();
        //            lblFinalSalaryData.Text = FinalSalaryMain = (Math.Ceiling(salary - advanceAmt + leavesAmt + otAmt - loanAmt - billAmt - pfAmt - esiAmt + double.Parse(lblAllowance.Text) + allowanceDeduct)).ToString();
        //            FinalSalaryWithOutBillsMain = (Math.Ceiling(salary - advanceAmt + leavesAmt + otAmt - loanAmt - pfAmt - esiAmt + double.Parse(lblAllowance.Text))).ToString();
        //            SanctLoanAmt = sanctionedAmt;
        //            double temp = 0d;
        //            if (double.TryParse(lblBalanceAmtData.Text, out temp))
        //                BalLoanAmt = temp;
        //            else
        //                BalLoanAmt = 0d;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        WriteToEventViewer(ex.Message);
        //        MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //    }
        //}

        private void cmbSelectedEmployee_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (cmbSelectedEmployee != null && cmbSelectedEmployee.SelectedValue != null)
                {
                    foreach (DataRow row in ((DataTable)cmbSelectedEmployee.DataSource).Rows)
                    {
                        if (cmbSelectedEmployee.SelectedValue.ToString() == row["EmpID"].ToString())
                        {
                            lblDeptInfo.Text = row["Department"].ToString();
                            lblBranchInfo.Text = row["Branch"].ToString();
                            lblDesignation.Text = row["Designation"].ToString();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnEmpSearch_Click(object sender, EventArgs e)
        {
            try
            {
                if (rbNameSearch.Checked)
                {
                    cmbSelectedEmployee.Enabled = true;
                    cmbSelectedEmployee.DataSource = null;

                    //if (Employees == null)
                    //    Employees = DBHelper.FetchEmployeesByName(txtNameSearch.Text.Trim());
                    cmbSelectedEmployee.DataSource = DBHelper.FetchEmployeesByName(txtNameSearch.Text.Trim(), true);
                    cmbSelectedEmployee.DisplayMember = "EmpIDName";
                    cmbSelectedEmployee.ValueMember = "EmpID";

                    if (cmbSelectedEmployee.SelectedIndex > -1)
                    {
                        foreach (DataRow row in ((DataTable)cmbSelectedEmployee.DataSource).Rows)
                        {
                            if (cmbSelectedEmployee.SelectedValue.ToString() == row["EmpID"].ToString())
                            {
                                lblDeptInfo.Text = row["Department"].ToString();
                                lblBranchInfo.Text = row["Branch"].ToString();
                                lblDesignation.Text = row["Designation"].ToString();
                            }
                        }
                    }
                    else
                    {
                        lblDeptInfo.Text = string.Empty;
                        lblDesignation.Text = string.Empty;
                        lblBranchInfo.Text = string.Empty;
                    }
                }
                else if (rbBranchDeptSearch.Checked)
                {
                    cmbSelectedEmployee.Enabled = true;
                    cmbSelectedEmployee.DataSource = null;

                    //if (cmbBranchSearch != null && cmbBranchSearch.SelectedValue != null && cmbDeptSearch != null && cmbDeptSearch.SelectedValue != null)
                    if (cmbBranchSearch != null && cmbBranchSearch.SelectedValue != null)
                    {
                        //Employees = DBHelper.FetchEmployeesByBranchandDept(cmbBranchSearch.SelectedValue.ToString(), cmbDeptSearch.SelectedValue.ToString());
                        Employees = DBHelper.FetchEmployeesByBranchandDept(cmbBranchSearch.SelectedValue.ToString());
                        cmbSelectedEmployee.DataSource = Employees;
                        cmbSelectedEmployee.DisplayMember = "EmpIDName";
                        cmbSelectedEmployee.ValueMember = "EmpID";

                        if (cmbSelectedEmployee.SelectedIndex > -1)
                        {
                            foreach (DataRow row in Employees.Rows)
                            {
                                if (cmbSelectedEmployee.SelectedValue.ToString() == row["EmpID"].ToString())
                                {
                                    lblDeptInfo.Text = row["Department"].ToString();
                                    lblDesignation.Text = row["Designation"].ToString();
                                    lblBranchInfo.Text = row["Branch"].ToString();
                                }
                            }
                        }
                        else
                        {
                            lblDeptInfo.Text = string.Empty;
                            lblDesignation.Text = string.Empty;
                            lblBranchInfo.Text = string.Empty;
                        }
                    }
                    else
                    {
                        MessageBox.Show("Please select Branch to proceed further", "Select Branch", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void searchRadioBtns_CheckedChanged(object sender, EventArgs e)
        {
            if (rbNameSearch.Checked)
            {
                DisplayNameFields();
            }
            else if (rbBranchDeptSearch.Checked)
            {
                DisplayBranchFields();
            }
        }

        private void DisplayNameSearchFields()
        {
            //txtNameSearch.Clear();
            //txtNameSearch.Enabled = true;

            //cmbBranchSearch.Enabled = false;
            //cmbDeptSearch.Enabled = false;

            switch (UserAction)
            {
                case (int)UserActionType.PaySalaryClick:
                    grpName.Text = "Salary Details";

                    break;
                case (int)UserActionType.PayAdvanceClick:
                    grpName.Text = "Advance Details";
                    break;
                case (int)UserActionType.PayOTClick:
                    grpName.Text = "OT Details";
                    break;
                case (int)UserActionType.PayBillClick:
                    grpName.Text = "Bills Details";
                    break;
                case (int)UserActionType.PayLeaveClick:
                    grpName.Text = "Leave Details";
                    break;
                case (int)UserActionType.AdvanceToLoan:
                    grpName.Text = "Advance To Loan Convertion";
                    break;
            }
        }

        private void DisplayNameFields()
        {
            txtNameSearch.Enabled = true;
            cmbBranchSearch.SelectedIndex = -1;
            cmbBranchSearch.Enabled = false;
        }

        private void DisplayBranchFields()
        {
            txtNameSearch.Clear();
            txtNameSearch.Enabled = false;
            cmbBranchSearch.Enabled = true;
            cmbBranchSearch.SelectedIndex = -1;
        }

        private DataTable GetMonthYears()
        {
            try
            {
                DataTable dtDates = new DataTable();
                dtDates.TableName = "Dates";

                dtDates.Columns.Add(new DataColumn("DateTime", typeof(DateTime)));
                dtDates.Columns.Add(new DataColumn("MonthYear", typeof(string)));
                int cnt = 1;
                if (DateTime.Now.Day > 10)
                    cnt = 1;
                else
                    cnt = 0;
                //if (DateTime.Now.Day > 10)
                //    cnt = 0;
                //else
                //    cnt = -1;
                for (; cnt > -12; cnt--)
                {
                    DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(cnt);
                    dtDates.Rows.Add(dt, dt.AddMonths(-1).ToString("MMM") + " " + dt.AddMonths(-1).ToString("yyyy") + " - " + dt.ToString("MMM") + " " + dt.ToString("yyyy"));
                }
                return dtDates;
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }

        private void btnPaySalaryData_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime salaryPayingMonth = DateTime.Parse(cmbMonth.SelectedValue.ToString());
                DateTime currentDate = DateTime.Now;

                if (txtLoanAmtData.Text.Trim() == string.Empty)
                {
                    txtLoanAmtData.Text = "0";
                }
                CurrentPaidAmt = double.Parse(txtLoanAmtData.Text);

                int result = DBHelper.PaySalary(empID,
                    //TODO : loanID == string.Empty ? "0" : loanID,
                                                "0",
                                                salaryPayingMonth.ToString("yyyy-MM-dd"),
                                                lblSalaryData.Text,
                                                lblAdvanceAmtData.Text,
                                                lblLeavesAmtData.Text,
                                                lblOTAmtData.Text,
                                                lblBillAmtData.Text,
                                                txtLoanAmtData.Text,
                                                lblPFAmtData.Text == string.Empty ? "0" : lblPFAmtData.Text,
                                                lblFinalSalaryData.Text,
                                                txtReduceBillAmt.Text == string.Empty ? "0" : txtReduceBillAmt.Text,
                                                lblLeavesCount.Tag.ToString(),
                                                lblOTCount.Tag.ToString(),
                                                txtExtraAmount.Text == string.Empty ? "0" : txtExtraAmount.Text,
                                                txtExtraAmtReason.Text,
                                                lblAllowance.Text == string.Empty ? "0" : lblAllowance.Text,
                                                txtReducedAllowanceAmt.Text == string.Empty ? "0" : txtReducedAllowanceAmt.Text,
                                                lblSanctionedAmtData.Text == string.Empty ? "0" : lblSanctionedAmtData.Text,
                                                lblBalanceAmtData.Text == string.Empty ? "0" : lblBalanceAmtData.Text
                                            );
                if (result > 0)
                {
                    MessageBox.Show("Added Salary Successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    lblSalaryPaidIcon.Visible = true;
                    txtLoanAmtData.Enabled = false;
                    btnPaySalaryData.Enabled = false;
                    txtReduceBillAmt.Enabled = false;
                    //lblSanctionedAmtData.Text = string.Empty;
                    //lblBalanceAmtData.Text = string.Empty;

                    //lblBalanceAmtData.Text = (BalLoanAmt - CurrentPaidAmt).ToString();

                    btnValidateLeaves.Enabled = false;
                    btnValidateOT.Enabled = false;
                    btnValidateAdvance.Enabled = false;
                    txtExtraAmount.Enabled = false;
                    txtExtraAmtReason.Enabled = false;
                    btnCalculate.Enabled = false;
                }
                else
                {
                    MessageBox.Show("Some unknown error has occurred. Please try later.", "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return;
        }

        private void btnAdvanceDetails_Click(object sender, EventArgs e)
        {
            //lblAlreadyAdvanceAmount.Text = "-";
            //txtAdvAmt.Clear();
            //dtAdvanceTaken.ResetText();

            //btnFinalPayAdvance.Enabled = true;
            //if (cmbSelectedEmployee == null || cmbSelectedEmployee.SelectedValue == null)
            //{
            //    MessageBox.Show("Please select the employee to proceed further.", "Select Employee", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    return;
            //}
            //lblAdvanceDetailsHeader.Text = "Advance Details for " + cmbSelectedEmployee.Text;
            //empID = cmbSelectedEmployee.SelectedValue.ToString();
            //lblSalaryAdvance.Text = Employees.Select(string.Format("EmpID = {0}", empID))[0]["Salary"].ToString();
            //DataTable dsAdvance = DBHelper.FetchCurrentMonthAdvanceDetails(empID);
            //if (dsAdvance != null && dsAdvance.Rows.Count > 0)
            //    lblAlreadyAdvanceAmount.Text = dsAdvance.Rows[0]["AdvanceAmt"].ToString();
            //if(lblAlreadyAdvanceAmount.Text.Trim() == string.Empty)
            //    lblAlreadyAdvanceAmount.Text = "-";
            //txtAdvAmt.Focus();
        }

        private void btnFinalPayAdvance_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtAdvAmt.Text.Trim() == string.Empty)
                {
                    MessageBox.Show("Please enter valid Advance Amount", "Enter Valid Amount", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                float salary = float.Parse(Employees.Select(string.Format("EmpID = {0}", empID))[0]["Salary"].ToString());
                float adv;
                if (!(float.TryParse(lblAlreadyAdvanceAmount.Text, out adv)))
                    adv = 0.0f;

                //if (salary / 2 < adv + float.Parse(txtAdvAmt.Text))
                //{
                //    MessageBox.Show("Advance can't be beyond half of your salary.", "Advance Limit Exceeds", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //    return;
                //}

                DateTime salDt;
                if (DateTime.Now.Day > 10)
                    salDt = new DateTime(DateTime.Now.Year, DateTime.Now.AddMonths(1).Month, 1);
                else
                    salDt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);

                DataTable dt = DBHelper.CheckWhetherSalaryPaid(empID, salDt);

                if (dt != null && dt.Rows.Count != 0)
                {
                    MessageBox.Show("Salary Paid for this month. Cannot Update Advance Amount.", "Invalid Operation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                int result = DBHelper.PayAdvanceOrBill(empID, txtAdvAmt.Text.Trim(), AdvanceOrBill.Advance, dtAdvanceTaken.Value);
                if (result < 0)
                {
                    MessageBox.Show("Some unknown error has occurred.", "Unknown Error.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else
                {
                    MessageBox.Show("Updated Successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    tabControl2.SelectTab(0);
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        private void btnOTDetails_Click(object sender, EventArgs e)
        {
            //dgShowOTDetails.DataSource = null;
            //dtOT.ResetText();

            //btnAddOT.Enabled = true;
            //if (cmbSelectedEmployee == null || cmbSelectedEmployee.SelectedValue == null)
            //{
            //    MessageBox.Show("Please select the employee to proceed further.", "Select Employee", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    return;
            //}
            //empID = cmbSelectedEmployee.SelectedValue.ToString();
            //lblOTDetailsHeader.Text = "O.T Details for " + cmbSelectedEmployee.Text;
            //dgShowOTDetails.DataSource = DBHelper.FetchLeaveAndOTDetails(empID).Tables[1];
        }

        private void btnOT_Click(object sender, EventArgs e)
        {
            try
            {
                if (cmbSelectedEmployee == null || cmbSelectedEmployee.SelectedValue == null)
                {
                    MessageBox.Show("Please select the employee to proceed further.", "Select Employee", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                dgShowOTDetails.DataSource = null;
                dtOT.ResetText();

                btnAddOT.Enabled = false;
                rbIsFullDayOT.Checked = true;
                List<DateTime> maxAndMinDates = GetMaxandMinDates();
                dtOT.MaxDate = maxAndMinDates[0];
                dtOT.MinDate = maxAndMinDates[1];
                UserAction = (int)UserActionType.PayOTClick;
                //ClearSearchFields();
                dgShowOTDetails.DataSource = null;
                //tabControl1.SelectTab(1);
                tabControl2.SelectTab(3);
                DisplayNameSearchFields();

                dgShowOTDetails.DataSource = null;
                dtOT.ResetText();

                btnAddOT.Enabled = true;

                empID = cmbSelectedEmployee.SelectedValue.ToString();
                lblOTDetailsHeader.Text = "O.T Details for " + cmbSelectedEmployee.Text;
                dgShowOTDetails.DataSource = DBHelper.FetchLeaveAndOTDetails(empID).Tables[1];
                dgShowOTDetails.Columns[0].Width = 40;
                dgShowOTDetails.Columns[1].Visible = false;
                dgShowOTDetails.Columns[2].Width = 90;
                dgShowOTDetails.Columns[3].Width = 70;
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAddOT_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime salDt;
                if (DateTime.Now.Day > 10)
                    salDt = new DateTime(DateTime.Now.Year, DateTime.Now.AddMonths(1).Month, 1);
                else
                    salDt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);

                DataTable dt = DBHelper.CheckWhetherSalaryPaid(empID, salDt);

                if (dt != null && dt.Rows.Count != 0)
                {
                    MessageBox.Show("Salary Paid for this month. Cannot update O.T's.", "Invalid Operation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                int result = DBHelper.AddLeaveOrOT(empID, LeaveOrOT.OT, dtOT.Value.ToString("MM/dd/yyyy"), rbIsHalfDayOT.Checked);
                if (result == -2)
                {
                    MessageBox.Show("Leave/O.T already added for this employee on this date.", "Already Added", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else if (result < 0)
                {
                    MessageBox.Show("Some unknown error has occurred.", "Unknown Error.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else
                {
                    MessageBox.Show("Added Successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    tabControl2.SelectTab(0);
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnGetLeaveDetails_Click(object sender, EventArgs e)
        {
            //dgLeaveDetails.DataSource = null;
            //dtLeaves.ResetText();

            //btnAddLeave.Enabled = true;
            //if (cmbSelectedEmployee == null || cmbSelectedEmployee.SelectedValue == null)
            //{
            //    MessageBox.Show("Please select the employee to proceed further.", "Select Employee", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    return;
            //}
            //empID = cmbSelectedEmployee.SelectedValue.ToString();
            //lblOTDetailsHeader.Text = "Leave Details for " + cmbSelectedEmployee.Text;
            //dgLeaveDetails.DataSource = DBHelper.FetchLeaveAndOTDetails(empID).Tables[0];
        }

        private void btnAddLeave_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime salDt;
                if (DateTime.Now.Day > 10)
                    salDt = new DateTime(DateTime.Now.Year, DateTime.Now.AddMonths(1).Month, 1);
                else
                    salDt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);

                DataTable dt = DBHelper.CheckWhetherSalaryPaid(empID, salDt);

                if (dt != null && dt.Rows.Count != 0)
                {
                    MessageBox.Show("Salary Paid for this month. Cannot Update Leaves.", "Invalid Operation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                int result = DBHelper.AddLeaveOrOT(empID, LeaveOrOT.Leave, dtLeaves.Value.ToString("MM/dd/yyyy"), rbIsHalfDayLeave.Checked);
                if (result == -2)
                {
                    MessageBox.Show("Leave/O.T already added for this employee on this date.", "Already Added", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else if (result < 0)
                {
                    MessageBox.Show("Some unknown error has occurred.", "Unknown Error.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else
                {
                    MessageBox.Show("Added Successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    tabControl2.SelectTab(0);
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAddLeaves_Click(object sender, EventArgs e)
        {
            try
            {
                if (cmbSelectedEmployee == null || cmbSelectedEmployee.SelectedValue == null)
                {
                    MessageBox.Show("Please select the employee to proceed further.", "Select Employee", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                dgLeaveDetails.DataSource = null;
                dtLeaves.ResetText();

                btnAddLeave.Enabled = false;
                List<DateTime> maxAndMinDates = GetMaxandMinDates();
                dtLeaves.MaxDate = maxAndMinDates[0];
                dtLeaves.MinDate = maxAndMinDates[1];
                UserAction = (int)UserActionType.PayLeaveClick;
                //ClearSearchFields();
                dgLeaveDetails.DataSource = null;
                //tabControl1.SelectTab(1);
                tabControl2.SelectTab(4);
                DisplayNameSearchFields();
                rbIsFullDayLeave.Checked = true;
                dgLeaveDetails.DataSource = null;
                dtLeaves.ResetText();

                btnAddLeave.Enabled = true;

                empID = cmbSelectedEmployee.SelectedValue.ToString();
                lblLeaveDetailsHeader.Text = "Leave Details for " + cmbSelectedEmployee.Text;
                dgLeaveDetails.DataSource = DBHelper.FetchLeaveAndOTDetails(empID).Tables[0];
                dgLeaveDetails.Columns[0].Width = 40;
                dgLeaveDetails.Columns[1].Visible = false;
                dgLeaveDetails.Columns[1].Width = 40;
                dgLeaveDetails.Columns[2].Width = 90;
                dgLeaveDetails.Columns[3].Width = 70;
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnGetBillDetails_Click(object sender, EventArgs e)
        {
            //lblPreviousBillAmt.Text = "-";
            //txtBillAmt.Clear();
            //dtBills.ResetText();

            //btnAddBills.Enabled = true;
            //if (cmbSelectedEmployee == null || cmbSelectedEmployee.SelectedValue == null)
            //{
            //    MessageBox.Show("Please select the employee to proceed further.", "Select Employee", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    return;
            //}
            //lblBillDetailsHeader.Text = "Bill Details for " + cmbSelectedEmployee.Text;
            //empID = cmbSelectedEmployee.SelectedValue.ToString();
            ////lblPreviousBillAmt.Text = Employees.Select(string.Format("EmpID = {0}", empID))[0]["Salary"].ToString();
            //DataTable dsBills = DBHelper.FetchCurrentBillDetails(empID);
            //if (dsBills != null && dsBills.Rows.Count > 0)
            //    lblPreviousBillAmt.Text = dsBills.Rows[0]["BillAmt"].ToString();
            //if (lblPreviousBillAmt.Text.Trim() == string.Empty)
            //    lblPreviousBillAmt.Text = "-";
            //txtBillAmt.Focus();
        }

        private void btnAddBillsMain_Click(object sender, EventArgs e)
        {
            try
            {
                if (cmbSelectedEmployee == null || cmbSelectedEmployee.SelectedValue == null)
                {
                    MessageBox.Show("Please select the employee to proceed further.", "Select Employee", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                lblPreviousBillAmt.Text = "-";
                txtBillAmt.Clear();
                dtBills.ResetText();

                btnAddBills.Enabled = false;
                List<DateTime> maxAndMinDates = GetMaxandMinDates();
                dtBills.MaxDate = maxAndMinDates[0];
                dtBills.MinDate = maxAndMinDates[1];
                UserAction = (int)UserActionType.PayBillClick;
                //ClearSearchFields();
                lblPreviousBillAmt.Text = string.Empty;
                txtBillAmt.Text = string.Empty;
                dgLeaveDetails.DataSource = null;
                //tabControl1.SelectTab(1);
                tabControl2.SelectTab(5);
                DisplayNameSearchFields();

                lblPreviousBillAmt.Text = "-";
                txtBillAmt.Clear();
                dtBills.ResetText();

                btnAddBills.Enabled = true;

                lblBillDetailsHeader.Text = "Bill Details for " + cmbSelectedEmployee.Text;
                empID = cmbSelectedEmployee.SelectedValue.ToString();
                //lblPreviousBillAmt.Text = Employees.Select(string.Format("EmpID = {0}", empID))[0]["Salary"].ToString();
                DataTable dsBills = DBHelper.FetchCurrentBillDetails(empID);
                if (dsBills != null && dsBills.Rows.Count > 0)
                    lblPreviousBillAmt.Text = dsBills.Rows[0]["BillAmt"].ToString();
                if (lblPreviousBillAmt.Text.Trim() == string.Empty)
                    lblPreviousBillAmt.Text = "-";
                txtBillAmt.Focus();
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAddBills_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime salDt;
                if (DateTime.Now.Day > 10)
                    salDt = new DateTime(DateTime.Now.Year, DateTime.Now.AddMonths(1).Month, 1);
                else
                    salDt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);

                DataTable dt = DBHelper.CheckWhetherSalaryPaid(empID, salDt);

                if (dt != null && dt.Rows.Count != 0)
                {
                    MessageBox.Show("Salary Paid for this month. Cannot Update Bill Amount.", "Invalid Operation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (txtBillAmt.Text.Trim() == string.Empty)
                {
                    MessageBox.Show("Please enter valid Bills Amount", "Enter Valid Amount", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                int result = DBHelper.PayAdvanceOrBill(empID, txtBillAmt.Text, AdvanceOrBill.Bill, dtBills.Value);
                if (result < 0)
                {
                    MessageBox.Show("Some unknown error has occurred.", "Unknown Error.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else
                {
                    MessageBox.Show("Updated Successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    tabControl2.SelectTab(0);
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtNameSearch_KeyUp(object sender, KeyEventArgs e)
        {
            btnEmpSearch_Click(sender, e);
        }

        private void cmbDeptSearch_KeyUp(object sender, KeyEventArgs e)
        {
            btnEmpSearch_Click(sender, e);
        }

        private void cmbBranchSearch_KeyUp(object sender, KeyEventArgs e)
        {
            btnEmpSearch_Click(sender, e);
        }

        private void btnAddUpdateEmployeeMain_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    dgEmployees.DataSource = null;
                    tabControl1.SelectTab(2);
                    txtEmpName.Clear();
                    dtpJoiningDate.ResetText();
                    cmbDepartmentType.DataSource = null;
                    cmbDesignationType.DataSource = null;
                    cmbBranch.DataSource = null;
                    txtSalary.Text = string.Empty;
                    txtReferredBy.Text = string.Empty;
                    txtPhoneNo.Text = string.Empty;
                    txtMobileNo.Text = string.Empty;
                    txtAddress.Text = string.Empty;
                    txtDocumentSubmitted.Text = string.Empty;
                    txtAllowances.Text = string.Empty;
                    btnAddUpdateEmployee_Click(sender, e);
                }
                catch (Exception ex)
                {
                    WriteToEventViewer(ex.Message);
                    MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabControl1.SelectTab(5);
                txtUserName.Focus();
            }
        }

        private void btnSearchEmp_Click(object sender, EventArgs e)
        {
            try
            {
                dgEmployees.DataSource = null;
                txtEmpName.Clear();
                txtEmpName.Enabled = false;
                dtpJoiningDate.Enabled = false;
                dtpJoiningDate.ResetText();
                cmbDepartmentType.DataSource = null;
                cmbDesignationType.DataSource = null;
                cmbBranch.DataSource = null;
                txtSalary.Text = string.Empty;

                PopulateEmployeeTabFields();
                dgEmployees.DataSource = DBHelper.FetchEmployeesByName(txtEmpSearchText.Text, false);
                dgEmployees.Columns[0].Width = 35;
                dgEmployees.Columns[0].HeaderText = "ID";
                dgEmployees.Columns[1].Width = 115;
                dgEmployees.Columns[3].Visible = false;
                dgEmployees.Columns[5].Visible = false;
                dgEmployees.Columns[7].Visible = false;
                dgEmployees.Columns[8].Width = 75;
                dgEmployees.Columns[9].Visible = false;
                dgEmployees.Columns[11].Visible = false;
                dgEmployees.Columns[12].Visible = false;
                dgEmployees.Columns[13].Visible = false;
                dgEmployees.Columns[14].Visible = false;
                dgEmployees.Columns[15].Visible = false;
                dgEmployees.Columns[17].Visible = false;
                dgEmployees.Columns[18].Visible = false;
                txtEmpName.Enabled = false;
                dgEmployees.Focus();
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            tabControl1.SelectTab(0);
        }

        private void txtEmpSearchText_KeyUp(object sender, KeyEventArgs e)
        {
            //btnSearchEmp_Click(sender, e);
        }

        private void dgEmployees_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (dgEmployees != null && dgEmployees.SelectedRows.Count > 0)
                {
                    DataGridViewRow row = dgEmployees.SelectedRows[0];
                    empID = dgEmployees.SelectedRows[0].Cells[0].Value.ToString();
                    txtEmpName.Text = row.Cells["EmpName"].Value.ToString();
                    string[] dateStrings = row.Cells["JoiningDate"].Value.ToString().Split('/');
                    dtpJoiningDate.Value = new DateTime(int.Parse(dateStrings[2]), int.Parse(dateStrings[1]), int.Parse(dateStrings[0]));
                    cmbDepartmentType.SelectedValue = row.Cells["DeptID"].Value.ToString();
                    cmbDesignationType.SelectedValue = row.Cells["DesignationID"].Value.ToString();
                    cmbBranch.SelectedValue = row.Cells["BranchID"].Value.ToString();
                    txtSalary.Text = row.Cells["Salary"].Value.ToString();
                    txtSalary.Enabled = false;

                    string tmp = row.Cells["ReferredBy"].Value.ToString();
                    if (tmp == "NULL")
                        txtReferredBy.Text = string.Empty;
                    else
                        txtReferredBy.Text = tmp;

                    tmp = row.Cells["PhoneNo"].Value.ToString();
                    if (tmp == "NULL")
                        txtPhoneNo.Text = string.Empty;
                    else
                        txtPhoneNo.Text = tmp;

                    tmp = row.Cells["MobileNo"].Value.ToString();
                    if (tmp == "NULL")
                        txtMobileNo.Text = string.Empty;
                    else
                        txtMobileNo.Text = tmp;

                    tmp = row.Cells["Address"].Value.ToString();
                    if (tmp == "NULL")
                        txtAddress.Text = string.Empty;
                    else
                        txtAddress.Text = tmp;

                    tmp = row.Cells["DocumentSubmitted"].Value.ToString();
                    if (tmp == "NULL")
                        txtDocumentSubmitted.Text = string.Empty;
                    else
                        txtDocumentSubmitted.Text = tmp;

                    if ((bool)row.Cells["IsPFIncluded"].Value)
                        cmbPFRequired.SelectedItem = "True";
                    else
                        cmbPFRequired.SelectedItem = "False";

                    if ((bool)row.Cells["IsLeavesConsidered"].Value)
                        cmbLeavesIncluded.SelectedItem = "True";
                    else
                        cmbLeavesIncluded.SelectedItem = "False";

                    if (bool.Parse(row.Cells["IsLeft"].Value.ToString()))
                        cmbIsLeft.SelectedIndex = 0;
                    else
                        cmbIsLeft.SelectedIndex = 1;

                    if (cmbPFRequired.SelectedIndex == 1)
                    {
                        txtPFAmt.Clear();
                        txtPFAmt.Enabled = false;
                    }
                    else
                    {
                        txtPFAmt.Text = row.Cells["PFAmount"].Value.ToString();
                        txtPFAmt.Enabled = true;
                    }

                    txtAllowances.Text = row.Cells["Allowance"].Value.ToString();
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void PopulateEmployeeTabFields()
        {
            try
            {
                if (Departments == null)
                    Departments = DBHelper.FetchDepartments();
                cmbDepartmentType.DataSource = Departments;
                cmbDepartmentType.DisplayMember = "Department";
                cmbDepartmentType.ValueMember = "DeptID";

                if (Branches == null)
                    Branches = DBHelper.FetchBranches();
                cmbBranch.DataSource = Branches;
                cmbBranch.DisplayMember = "Branch";
                cmbBranch.ValueMember = "BranchID";

                if (Designations == null)
                    Designations = DBHelper.FetchDesignations();
                cmbDesignationType.DataSource = Designations;
                cmbDesignationType.DisplayMember = "Designation";
                cmbDesignationType.ValueMember = "DesignationID";
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAddUpdateEmployee_Click(object sender, EventArgs e)
        {
            try
            {
                MessageBox.Show("Fill the below details and click on Add/Update Employee.", "Add Employee", MessageBoxButtons.OK, MessageBoxIcon.Information);
                PopulateEmployeeTabFields();
                dgEmployees.DataSource = null;
                txtEmpName.Clear();
                dtpJoiningDate.ResetText();
                cmbDepartmentType.SelectedIndex = 0;
                cmbDesignationType.SelectedIndex = 0;
                cmbBranch.SelectedIndex = 0;
                txtSalary.ResetText();
                dtpJoiningDate.Enabled = true;
                txtEmpName.Enabled = true;
                txtReferredBy.ResetText();
                txtPhoneNo.ResetText();
                txtMobileNo.ResetText();
                txtAddress.ResetText();
                txtDocumentSubmitted.ResetText();
                txtEmpName.Focus();
                txtSalary.Enabled = true;
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAddorUpdateEmployee_Click(object sender, EventArgs e)
        {
            try
            {
                string id = string.Empty;
                if (dgEmployees.DataSource != null && empID != string.Empty)
                {
                    id = empID;
                }

                int res = DBHelper.AddorUpdateEmployee(id == string.Empty ? "0" : id, txtEmpName.Text, dtpJoiningDate.Value.ToString("MM/dd/yyyy"), cmbDepartmentType.SelectedValue.ToString(), cmbBranch.SelectedValue.ToString(), txtSalary.Text,
                    Convert.ToBoolean(cmbPFRequired.Text) ? 1 : 0, txtPhoneNo.Text, txtMobileNo.Text, txtAddress.Text, txtReferredBy.Text, txtDocumentSubmitted.Text, cmbDesignationType.SelectedValue.ToString(), Convert.ToBoolean(cmbLeavesIncluded.Text) ? 1 : 0,
                    cmbIsLeft.Text, txtPFAmt.Text, txtAllowances.Text == string.Empty ? "0" : txtAllowances.Text);

                if (res > 0)
                {
                    MessageBox.Show("Updated Successfully.", "Updated", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    dgEmployees.DataSource = DBHelper.FetchEmployeesByName(txtEmpSearchText.Text, true);
                    Employees = DBHelper.FetchEmployeesByName(txtNameSearch.Text.Trim(), true);
                    txtEmpName.ResetText();
                    dtpJoiningDate.ResetText();
                    cmbDepartmentType.ResetText();
                    cmbDesignationType.ResetText();
                    cmbBranch.ResetText();
                    txtSalary.ResetText();
                    cmbPFRequired.ResetText();
                    txtReferredBy.ResetText();
                    txtPhoneNo.ResetText();
                    txtMobileNo.ResetText();
                    txtDocumentSubmitted.ResetText();
                    txtAddress.ResetText();
                    cmbLeavesIncluded.ResetText();
                }
                else
                {
                    MessageBox.Show("Some unknown error has occurred.", "Unknown Error.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                return;
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAddItem_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                tabControl1.SelectTab(3);
            }
            else
            {
                tabControl1.SelectTab(5);
                txtUserName.Focus();
            }
        }

        private void btnEmployeesWithLoans_Click(object sender, EventArgs e)
        {
            try
            {
                lblEmployeesWithLoans.Text = "Employees Having Loans";
                dgEmployeesDetails.DataSource = DBHelper.FetchEmployeesWithLoans();
                dgEmployeesDetails.Columns[0].Width = 30;
                dgEmployeesDetails.Columns[0].HeaderText = "ID";
                dgEmployeesDetails.Columns[1].Width = 155;
                dgEmployeesDetails.Columns[2].Width = 70;
                dgEmployeesDetails.Columns[4].Visible = false;
                dgEmployeesDetails.Columns[6].Visible = false;
                dgEmployeesDetails.Columns[8].Width = 60;
                //btnAddNewLoan.Enabled = false;

                if (Departments == null)
                    Departments = DBHelper.FetchDepartments();
                //cmbDeptLoan.DataSource = Departments;
                //cmbDeptLoan.DisplayMember = "Department";
                //cmbDeptLoan.ValueMember = "DeptID";
                //cmbDeptLoan.SelectedIndex = -1;

                if (Branches == null)
                    Branches = DBHelper.FetchBranches();
                //cmbBranchLoan.DataSource = Branches;
                //cmbBranchLoan.DisplayMember = "Branch";
                //cmbBranchLoan.ValueMember = "BranchID";
                //cmbBranchLoan.SelectedIndex = -1;
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnEmployeesWithoutLoans_Click(object sender, EventArgs e)
        {
            try
            {
                lblEmployeesWithLoans.Text = "Employees Without Having Loans";
                dgEmployeesDetails.DataSource = DBHelper.FetchEmployeesWithoutLoans();
                dgEmployeesDetails.Columns[0].Width = 60;
                dgEmployeesDetails.Columns[4].Visible = false;
                dgEmployeesDetails.Columns[6].Visible = false;
                btnAddNewLoan.Enabled = true;
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgEmployeesDetails_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (dgEmployeesDetails.SelectedRows.Count > 0)// && dgEmployeesDetails.Columns.Count > 6)
                {
                    txtEmpNameLoan.Text = dgEmployeesDetails.SelectedRows[0].Cells["EmpName"].Value.ToString();
                    string[] date = dgEmployeesDetails.SelectedRows[0].Cells["JoiningDate"].Value.ToString().Split('/');
                    dtpJoiningDateLoan.Value = new DateTime(int.Parse(date[2]), int.Parse(date[1]), int.Parse(date[0]));
                    //cmbDepartmentType.SelectedValue = dgEmployeesDetails.SelectedRows[0].Cells["DeptID"].Value.ToString();
                    if (dgEmployeesDetails.ColumnCount > 8)
                    {
                        lblExistingLoanAmt.Text = dgEmployeesDetails.SelectedRows[0].Cells["IssuedAmount"].Value.ToString();
                        lblBalanceLoanAmt.Text = DBHelper.FetchRepayedAmount(dgEmployeesDetails.SelectedRows[0].Cells["EmpID"].Value.ToString());
                    }
                    else
                    {
                        lblExistingLoanAmt.Text = string.Empty;
                        lblBalanceLoanAmt.Text = string.Empty;
                    }
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnOperations_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    tabControl1.SelectTab(1);
                    tabControl2.SelectTab(0);
                    cmbSelectedEmployee.DataSource = null;
                    lblDeptInfo.Text = string.Empty;
                    lblDesignation.Text = string.Empty;
                    lblBranchInfo.Text = string.Empty;
                    if (Branches == null)
                        Branches = DBHelper.FetchBranches();
                    cmbBranchSearch.DataSource = Branches;
                    cmbBranchSearch.DisplayMember = "Branch";
                    cmbBranchSearch.ValueMember = "BranchID";
                    cmbBranchSearch.SelectedIndex = -1;
                }
                catch (Exception ex)
                {
                    WriteToEventViewer(ex.Message);
                    MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabControl1.SelectTab(5);
                txtUserName.Focus();
            }
        }

        private void btnConvertAdvanceToLoan_Click(object sender, EventArgs e)
        {
            try
            {
                if (cmbSelectedEmployee == null || cmbSelectedEmployee.SelectedValue == null)
                {
                    MessageBox.Show("Please select the employee to proceed further.", "Select Employee", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                //lblAdvanceTaken.Text = "-";
                //lblAdvanceToLoanHeader.Text = "Advance -> Loan for " + cmbSelectedEmployee.Text;
                UserAction = (int)UserActionType.AdvanceToLoan;
                tabControl2.SelectTab(10);
                DisplayNameSearchFields();
                btnLoanConvert.Enabled = false;
                empID = cmbSelectedEmployee.SelectedValue.ToString();

                DataTable dsAdvance = DBHelper.FetchCurrentMonthAdvanceDetails(empID);
                if (dsAdvance != null && dsAdvance.Rows.Count > 0)
                {
                    dgAdvToLoan.DataSource = dsAdvance;
                    //double adv = 0d;
                    //foreach (DataRow dr in dsAdvance.Rows)
                    //    adv += double.Parse(dr["AdvanceAmt"].ToString());
                    //lblAdvanceTaken.Text = adv.ToString();
                    btnLoanConvert.Enabled = true;
                    dgAdvToLoan.Columns[0].Width = 40;
                    dgAdvToLoan.Columns[1].Visible = false;
                    dgAdvToLoan.Columns[2].Visible = false;
                    dgAdvToLoan.Columns[3].Width = 90;
                    dgAdvToLoan.Columns[4].Width = 70;
                    dgAdvToLoan.Columns[5].Width = 55;
                    dgAdvToLoan.Columns[0].ReadOnly = true;
                    dgAdvToLoan.Columns[3].ReadOnly = true;
                    dgAdvToLoan.Columns[4].ReadOnly = true;
                    dgAdvToLoan.Columns[5].ReadOnly = false;
                    dgAdvToLoan.Columns[5].HeaderText = "Convert";
                }
                else
                {
                    MessageBox.Show("There are no advance details available for this employee", "No Advance Details", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    tabControl2.SelectTab(0);
                    btnLoanConvert.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /*private void btnConvertAdvanceToLoan_Click(object sender, EventArgs e)
        {
            try
            {
                if (cmbSelectedEmployee == null || cmbSelectedEmployee.SelectedValue == null)
                {
                    MessageBox.Show("Please select the employee to proceed further.", "Select Employee", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                lblAdvanceTaken.Text = "-";
                lblAdvanceToLoanHeader.Text = "Advance -> Loan for " + cmbSelectedEmployee.Text;
                UserAction = (int)UserActionType.AdvanceToLoan;
                tabControl2.SelectTab(6);
                DisplayNameSearchFields();
                btnConvertToLoan.Enabled = false;
                empID = cmbSelectedEmployee.SelectedValue.ToString();

                lblAdvanceTaken.Text = "-";

                DataTable dsAdvance = DBHelper.FetchCurrentMonthAdvanceDetails(empID);
                if (dsAdvance != null && dsAdvance.Rows.Count > 0)
                {
                    double adv = 0d;
                    foreach (DataRow dr in dsAdvance.Rows)
                        adv += double.Parse(dr["AdvanceAmt"].ToString());
                    lblAdvanceTaken.Text = adv.ToString();
                    btnConvertToLoan.Enabled = true;
                }
                if (lblAdvanceTaken.Text.Trim() == string.Empty)
                {
                    lblAdvanceTaken.Text = "-";
                    MessageBox.Show("There are no advance details available for this employee", "No Advance Details", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    tabControl2.SelectTab(0);
                    btnConvertToLoan.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }*/

        private void btnFetchAdvanceDetails_Click(object sender, EventArgs e)
        {
            //lblAdvanceTaken.Text = "-";

            //DataTable dsAdvance = DBHelper.FetchCurrentMonthAdvanceDetails(empID);
            //if (dsAdvance != null && dsAdvance.Rows.Count > 0)
            //{
            //    lblAdvanceTaken.Text = dsAdvance.Rows[0]["AdvanceAmt"].ToString();
            //    btnConvertToLoan.Enabled = true;
            //}
            //if (lblAlreadyAdvanceAmount.Text.Trim() == string.Empty)
            //{
            //    lblAdvanceTaken.Text = "-";
            //    MessageBox.Show("There are no advance details available for this employee", "No Advance Details", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    tabControl2.SelectTab(0);
            //}
        }

        private void btnConvertToLoan_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime salDt;
                if (DateTime.Now.Day > 10)
                {
                    salDt = new DateTime(DateTime.Now.Year, DateTime.Now.AddMonths(1).Month, 1);
                }
                else
                {
                    salDt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
                }

                DataTable dt = DBHelper.CheckWhetherSalaryPaid(empID, salDt);

                if (dt != null && dt.Rows.Count != 0)
                {
                    MessageBox.Show("Salary Paid for this month. Cannot Convert Advance To Loan.", "Invalid Operation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                int res = DBHelper.ConvertAdvanceToLoan(empID);
                if (res >= 0)
                {
                    MessageBox.Show("Updated Successfully. LoanID : " + res, "COnverted To Loan", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    tabControl2.SelectTab(0);
                    return;
                }
                else
                {
                    MessageBox.Show("Some unknown error has occurred.", "Unknown Error.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtSalary_TextChanged(object sender, EventArgs e)
        {
            try
            {
                double value;
                if (!double.TryParse(txtSalary.Text, out value))
                {
                    txtSalary.Text = string.Empty;
                }
                //else
                //{
                //    lblTenDaysSal.Text = Math.Ceiling((value / 3)).ToString();
                //}
                return;
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtAdvAmt_TextChanged(object sender, EventArgs e)
        {
            try
            {
                double value;
                if (!double.TryParse(txtAdvAmt.Text, out value))
                    txtAdvAmt.Text = string.Empty;
                return;
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtBillAmt_TextChanged(object sender, EventArgs e)
        {
            try
            {
                double value;
                if (!double.TryParse(txtBillAmt.Text, out value))
                    txtBillAmt.Text = string.Empty;
                return;
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAddNewLoan_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgEmployeesDetails != null && dgEmployeesDetails.Rows.Count > 0 && dgEmployeesDetails.SelectedRows.Count > 0)
                {
                    double value;
                    empID = dgEmployeesDetails.SelectedRows[0].Cells[0].Value.ToString();
                    if (!(double.TryParse(txtLoanAmt.Text, out value)))
                    {
                        MessageBox.Show("Enter valid value in Loan Amount Field", "Loan Amout Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    if (DBHelper.ApplyLoanByEmpID(empID, txtLoanAmt.Text) < 1)
                        MessageBox.Show("Some Unknown Error Has Ocurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    else
                    {
                        MessageBox.Show("Loan Sanctioned Successfully", "Sanctioned", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        dgEmployeesDetails.DataSource = null;
                        txtEmpNameLoan.Text = string.Empty;
                        dtpJoiningDate.ResetText();
                        lblExistingLoanAmt.Text = string.Empty;
                        lblBalanceLoanAmt.Text = string.Empty;
                        txtLoanAmt.Text = string.Empty;
                    }
                }
                else
                {
                    MessageBox.Show("Not have Valid Details", "Invalid Details", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnLoanReport_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    tabControl1.SelectTab(4);
                    //dgEmployeeLoans.DataSource = null;
                    //dgLoanCompleteDetails.DataSource = null;

                    //DataTable dt = new DataTable();
                    //dt.Columns.Add("EmpID");
                    //dt.Columns.Add("EmpName");

                    //if (Employees == null)
                    //    Employees = DBHelper.FetchEmployeesByName(txtNameSearch.Text.Trim());

                    //foreach (DataRow row in Employees.Rows)
                    //{
                    //    DataRow dr = dt.NewRow();
                    //    dr[0] = row["EmpID"].ToString();
                    //    dr[1] = row["EmpName"].ToString() + " - " + row["Department"].ToString() + " - " + row["Branch"].ToString();
                    //    dt.Rows.Add(dr);
                    //}
                    //cmbEmpList.DataSource = dt;
                    //cmbEmpList.ValueMember = "EmpID";
                    //cmbEmpList.DisplayMember = "EmpName";
                }
                catch (Exception ex)
                {
                    WriteToEventViewer(ex.Message);
                    MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabControl1.SelectTab(5);
                txtUserName.Focus();
            }
        }

        private void btnFetchLoans_Click(object sender, EventArgs e)
        {
            try
            {
                dgEmployeeLoans.DataSource = DBHelper.FetchLoansByEmpID(cmbEmpList.SelectedValue.ToString());
                dgEmployeeLoans.Columns[0].Width = 60;
                if (dgEmployeeLoans.DataSource == null || dgEmployeeLoans.Rows.Count == 0)
                    dgLoanCompleteDetails.DataSource = null;
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgEmployeeLoans_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (dgEmployeeLoans != null && dgEmployeeLoans.SelectedRows.Count > 0)
                {
                    string loanID = ((DataGridView)(sender)).SelectedRows[0].Cells[0].Value.ToString();
                    DataTable dtValues = DBHelper.FetchLoanDetailsByLoanID(loanID);

                    double balance = 0d;

                    for (int cnt = 0; cnt < dtValues.Rows.Count; cnt++)
                    {
                        if (dtValues.Rows[cnt]["Action"].ToString() == "Sanctioned")
                        {
                            try
                            {
                                balance += double.Parse(dtValues.Rows[cnt]["Amount"].ToString());
                            }
                            catch (Exception) { }
                        }
                        else if (dtValues.Rows[cnt]["Action"].ToString() == "Installment Paid")
                        {
                            try
                            {
                                balance -= double.Parse(dtValues.Rows[cnt]["Amount"].ToString());
                            }
                            catch (Exception) { }
                        }

                        DataRow row = dtValues.NewRow();
                        row["ID"] = DBNull.Value;
                        row["Action"] = "Balance";
                        row["Amount"] = balance;

                        dtValues.Rows.InsertAt(row, cnt + 1);
                        cnt++;
                    }

                    dgLoanCompleteDetails.DataSource = dtValues;
                    dgLoanCompleteDetails.Columns[0].Width = 50;
                    dgLoanCompleteDetails.Columns[1].Width = 200;
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            try
            {
                if (lblSalaryPaidIcon.Visible)
                {
                    PrintDGV.Header = lblSalaryDetailsHeader.Text;
                    PrintDGV.SalaryAmt = lblSalaryData.Text;
                    PrintDGV.AdvanceAmt = lblAdvanceAmtData.Text;
                    PrintDGV.LeavesAmt = lblLeavesAmtData.Text;
                    PrintDGV.OTAmt = lblOTAmtData.Text;
                    PrintDGV.BillsAmt = lblBillAmtData.Text;
                    PrintDGV.DeductionsAmt = txtReduceBillAmt.Text;
                    PrintDGV.PFAmt = lblPFAmtData.Text;
                    PrintDGV.LoanAmt = txtLoanAmtData.Text;
                    //PrintDGV.LoanSanctionedAmt = lblSanctionedAmtData.Text;
                    //PrintDGV.LoanBalanceAmt = lblBalanceAmtData.Text;
                    PrintDGV.LoanSanctionedAmt = SanctLoanAmt.ToString();
                    PrintDGV.LoanBalanceAmt = lblBalanceAmtData.Text;
                    PrintDGV.CurrentLoanAmt = lblBalanceAmtData.Text;
                    PrintDGV.FinalSalaryAmt = lblFinalSalaryData.Text;
                    PrintDGV.LeavesCount = lblLeavesCount.Tag.ToString();
                    PrintDGV.OTCount = lblOTCount.Tag.ToString();
                    PrintDGV.ExtraAmount = txtExtraAmount.Text;
                    PrintDGV.ExtraAmountReason = txtExtraAmtReason.Text;
                    PrintDGV.Allowance = lblAllowance.Text;
                    //PrintDGV.CurrentLoanAmt = lblBalanceAmtData.Text;
                    PrintDGV.Print_SalaryData();
                }
                else
                {
                    MessageBox.Show("Pay Salary Before Printing.", "Salary Not Paid", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtUserName.Text.Trim().ToLower() == "ksbakers.salaries" || txtPassword.Text.Trim().ToLower() == "salaries." + DateTime.Now.ToString("ddMMyyyy"))
                {
                    IsLoggedIn = true;
                    tabControl1.SelectTab(0);
                    return;
                }
                else
                {
                    MessageBox.Show("Invalid Details", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtPassword.Clear();
                    txtPassword.Focus();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            //for (int cnt = 1; cnt <= 5; cnt++)
            //{
            //    string user = ConfigurationManager.AppSettings["User" + cnt.ToString()];
            //    string pass = ConfigurationManager.AppSettings["P" + cnt.ToString()];

            //    if (user != null)
            //    {
            //        if (txtUserName.Text == user && txtPassword.Text == pass)
            //        {
            //            IsLoggedIn = true;
            //            tabControl1.SelectTab(0);
            //            return;
            //        }
            //    }
            //    else
            //    {
            //        MessageBox.Show("Invalid Login Details", "Invalid Login", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //        //txtUserName.Text = string.Empty;
            //        txtPassword.Text = string.Empty;
            //        break;
            //    }
            //}
        }

        private void txtPassword_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                btnLogin_Click(sender, e);
        }

        private void btnSearchLoanEmp_Click(object sender, EventArgs e)
        {
            try
            {
                dgEmployeeLoans.DataSource = null;
                dgLoanCompleteDetails.DataSource = null;

                DataTable dt = new DataTable();
                dt.Columns.Add("EmpID");
                dt.Columns.Add("EmpName");

                if (Employees == null)
                    Employees = DBHelper.FetchEmployeesByName(txtNameSearch.Text.Trim(), true);

                cmbEmpList.DataSource = null;

                foreach (DataRow row in Employees.Rows)
                {
                    if (txtSearch.Text.Trim() != string.Empty)
                        if (!(row["EmpName"].ToString().StartsWith(txtSearch.Text.Trim()) || row["EmpName"].ToString().ToUpper().StartsWith(txtSearch.Text.Trim().ToUpper()) || row["EmpID"].ToString().StartsWith(txtSearch.Text.Trim())))
                            continue;

                    DataRow dr = dt.NewRow();
                    dr[0] = row["EmpID"].ToString();
                    dr[1] = row["EmpID"].ToString() + " - " + row["EmpName"].ToString() + " - " + row["Department"].ToString() + " - " + row["Branch"].ToString();
                    dt.Rows.Add(dr);
                }
                cmbEmpList.DataSource = dt;
                cmbEmpList.ValueMember = "EmpID";
                cmbEmpList.DisplayMember = "EmpName";
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnValidateLeaves_Click(object sender, EventArgs e)
        {
            tabControl2.SelectTab(7);
            dgvValidateLeaves.DataSource = ValidateLeaves;
            dgvValidateLeaves.Columns[0].Width = 40;
            dgvValidateLeaves.Columns[1].Visible = false;
            dgvValidateLeaves.Columns[2].Visible = false;
            dgvValidateLeaves.Columns[3].Width = 90;
            dgvValidateLeaves.Columns[4].Width = 70;
            dgvValidateLeaves.Columns[5].Width = 35;
            dgvValidateLeaves.Columns[0].ReadOnly = true;
            dgvValidateLeaves.Columns[3].ReadOnly = true;
            dgvValidateLeaves.Columns[4].ReadOnly = true;
            dgvValidateLeaves.Columns[5].ReadOnly = false;
        }

        private void btnValidateOT_Click(object sender, EventArgs e)
        {
            tabControl2.SelectTab(8);
            dgvValidateOTs.DataSource = ValidateOTs;
            dgvValidateOTs.Columns[0].Width = 40;
            dgvValidateOTs.Columns[1].Visible = false;
            dgvValidateOTs.Columns[2].Visible = false;
            dgvValidateOTs.Columns[3].Width = 90;
            dgvValidateOTs.Columns[4].Width = 70;
            dgvValidateOTs.Columns[5].Width = 35;
            dgvValidateOTs.Columns[0].ReadOnly = true;
            dgvValidateOTs.Columns[3].ReadOnly = true;
            dgvValidateOTs.Columns[4].ReadOnly = true;
            dgvValidateOTs.Columns[5].ReadOnly = false;
        }

        private void btnValidateAdvance_Click(object sender, EventArgs e)
        {
            tabControl2.SelectTab(9);
            dgvValidateAdvance.DataSource = ValidateAdvance;
            dgvValidateAdvance.Columns[0].Width = 40;
            dgvValidateAdvance.Columns[1].Visible = false;
            dgvValidateAdvance.Columns[2].Visible = false;
            dgvValidateAdvance.Columns[3].Width = 90;
            dgvValidateAdvance.Columns[4].Width = 70;
            dgvValidateAdvance.Columns[5].Width = 35;
            dgvValidateAdvance.Columns[0].ReadOnly = true;
            dgvValidateAdvance.Columns[3].ReadOnly = true;
            dgvValidateAdvance.Columns[4].ReadOnly = true;
            dgvValidateAdvance.Columns[5].ReadOnly = false;
        }

        private void btnUpdateValid_Click(object sender, EventArgs e)
        {
            try
            {
                if ((sender as Button).Name == "btnUpdateValidLeaves")
                {
                    foreach (DataGridViewRow row in dgvValidateLeaves.Rows)
                    {
                        if (!(DBHelper.UpdateValidatingCreditTransaction(row.Cells[1].Value.ToString(), bool.Parse(row.Cells[5].Value.ToString()))))
                            throw new Exception("Custom Error - Update Failed");
                    }
                }
                else if ((sender as Button).Name == "btnUpdateOTs")
                {
                    foreach (DataGridViewRow row in dgvValidateOTs.Rows)
                    {
                        if (!(DBHelper.UpdateValidatingCreditTransaction(row.Cells[1].Value.ToString(), bool.Parse(row.Cells[5].Value.ToString()))))
                            throw new Exception("Custom Error - Update Failed");
                    }
                }
                else if ((sender as Button).Name == "btnUpdateAdvance")
                {
                    foreach (DataGridViewRow row in dgvValidateAdvance.Rows)
                    {
                        if (!(DBHelper.UpdateValidatingDebitTransaction(row.Cells[1].Value.ToString(), bool.Parse(row.Cells[5].Value.ToString()))))
                            throw new Exception("Custom Error - Update Failed");
                    }
                }

                MessageBox.Show("Updated Successfully", "Updated", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnBack_Click_1(object sender, EventArgs e)
        {
            FillUnPaidSalaryDetailsLatest();
            tabControl2.SelectTab(1);
        }

        private void btnSalaryReport_Click(object sender, EventArgs e)
        {
            try
            {
                if (IsLoggedIn)
                {
                    try
                    {
                        tabControl1.SelectTab(6);
                        lblTotalSalary.Text = string.Empty;
                        if (cmbBranchesSalReport.DataSource == null)
                        {
                            DataTable dtBranches = DBHelper.FetchBranches();
                            dtBranches.Rows.Add(0, "All");
                            cmbBranchesSalReport.DataSource = dtBranches;
                            cmbBranchesSalReport.DisplayMember = "Branch";
                            cmbBranchesSalReport.ValueMember = "BranchID";
                            cmbBranchesSalReport.SelectedIndex = 0;
                        }

                        if (cmbMonthsSalReport.DataSource == null)
                        {
                            cmbMonthsSalReport.DataSource = GetMonthYears();
                            cmbMonthsSalReport.DisplayMember = "MonthYear";
                            cmbMonthsSalReport.ValueMember = "DateTime";
                        }

                        cmbSalPaidUnPaid.SelectedIndex = 0;
                    }
                    catch (Exception)
                    { }
                }
                else
                {
                    tabControl1.SelectTab(5);
                    txtUserName.Focus();
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSalariesReport_Click(object sender, EventArgs e)
        {
            try
            {
                //cmbSalPaidUnPaid.SelectedItem == null || 
                if (cmbBranchesSalReport == null || cmbBranchesSalReport.SelectedValue == null || cmbMonthsSalReport == null || cmbMonthsSalReport.SelectedValue == null)
                {
                    MessageBox.Show("Please select the Branch & Month to proceed further.", "Select Mandatory Details", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                bool isPaid = false;
                if (cmbSalPaidUnPaid.SelectedItem.ToString() == "Paid")
                    isPaid = true;
                //DataSet ds = DBHelper.FetchSalaryPaidAndUnPaidDetails(isPaid, cmbBranchesSalReport.SelectedValue.ToString(), DateTime.Parse(cmbMonthsSalReport.SelectedValue.ToString()));

                DataSet ds = DBHelper.FetchSalaryPaidAndUnPaidDetails(cmbBranchesSalReport.SelectedValue.ToString(), DateTime.Parse(cmbMonthsSalReport.SelectedValue.ToString()), isPaid, chkResigned.Checked);
                Font font = new Font("Arial", 11, FontStyle.Regular);

                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    dgSalariesReport.DataSource = ds.Tables[0];
                    if (isPaid)
                    {
                        double value = 0;
                        if (double.TryParse(ds.Tables[1].Rows[0][0].ToString(), out value))
                        {
                            lblTotalSalary.Text = "Total Amount Paid = " + value.ToString("c");
                        }

                        dgSalariesReport.Columns[0].Width = 50;
                        dgSalariesReport.Columns[1].Width = 150;
                        dgSalariesReport.Columns[9].Visible = false;

                        if (chkResigned.Checked)
                        {
                            foreach (DataGridViewRow row in dgSalariesReport.Rows)
                            {
                                if (row.Cells[5].Value.ToString() == "True")
                                {
                                    row.Cells[0].Style = new DataGridViewCellStyle { BackColor = Color.LightGray, Font = font };
                                    row.Cells[1].Style = new DataGridViewCellStyle { BackColor = Color.LightGray, Font = font };
                                    row.Cells[2].Style = new DataGridViewCellStyle { BackColor = Color.LightGray, Font = font };
                                    row.Cells[3].Style = new DataGridViewCellStyle { BackColor = Color.LightGray, Font = font };
                                    row.Cells[4].Style = new DataGridViewCellStyle { BackColor = Color.LightGray, Font = font };
                                }
                            }
                        }
                    }
                    else
                    {
                        dgSalariesReport.Columns[0].Width = 50;
                        dgSalariesReport.Columns[1].Width = 200;
                        dgSalariesReport.Columns[3].Width = 200;
                        dgSalariesReport.Columns[5].Visible = false;
                        lblTotalSalary.Text = string.Empty;

                        if (chkResigned.Checked)
                        {
                            foreach (DataGridViewRow row in dgSalariesReport.Rows)
                            {
                                if (row.Cells[5].Value.ToString() == "True")
                                {
                                    row.Cells[0].Style = new DataGridViewCellStyle { BackColor = Color.LightGray, Font = font };
                                    row.Cells[1].Style = new DataGridViewCellStyle { BackColor = Color.LightGray, Font = font };
                                    row.Cells[2].Style = new DataGridViewCellStyle { BackColor = Color.LightGray, Font = font };
                                    row.Cells[3].Style = new DataGridViewCellStyle { BackColor = Color.LightGray, Font = font };
                                    row.Cells[4].Style = new DataGridViewCellStyle { BackColor = Color.LightGray, Font = font };
                                }
                            }
                        }
                    }
                }
                else
                {
                    dgSalariesReport.DataSource = null;
                    lblTotalSalary.Text = string.Empty;
                    MessageBox.Show("No Data Available", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnEmpSearchLoan_Click(object sender, EventArgs e)
        {
            lblEmployeesWithLoans.Text = "Employees Having Loans";
            dgEmployeesDetails.DataSource = DBHelper.FetchEmployeeLoanDetails(txtEmpSearch.Text);
            dgEmployeesDetails.Columns[0].Width = 30;
            dgEmployeesDetails.Columns[0].HeaderText = "ID";
            dgEmployeesDetails.Columns[1].Width = 155;
            dgEmployeesDetails.Columns[2].Width = 70;
            dgEmployeesDetails.Columns[4].Visible = false;
            dgEmployeesDetails.Columns[6].Visible = false;
            dgEmployeesDetails.Columns[8].Width = 60;
        }

        private void btnLoanConvert_Click(object sender, EventArgs e)
        {
            try
            {
                if (DBHelper.ConvertSomeAdvancesToLoan(empID, dgAdvToLoan))
                {
                    MessageBox.Show("Advances Converted Successfully", "Converted Successfully", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    btnConvertAdvanceToLoan_Click(sender, e);
                }
                else
                {
                    MessageBox.Show("Some unknown error has occurred.", "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnEmpDetails_Click(object sender, EventArgs e)
        {
            try
            {
                if (IsLoggedIn)
                {
                    tabControl1.SelectTab(7);

                    if (cmbBranchesAllEmployees.DataSource == null)
                    {
                        DataTable dtBranches = DBHelper.FetchBranches();
                        dtBranches.Rows.Add(0, "All");
                        cmbBranchesAllEmployees.DataSource = dtBranches;
                        cmbBranchesAllEmployees.DisplayMember = "Branch";
                        cmbBranchesAllEmployees.ValueMember = "BranchID";
                        cmbBranchesAllEmployees.SelectedIndex = 0;
                        cmbYear.SelectedIndex = 0;
                    }
                }
                else
                {
                    tabControl1.SelectTab(5);
                    txtUserName.Focus();
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnGetEmployees_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                btnSaveEmployeeDetails.Enabled = !chkResignedEmployees.Checked;

                dgEmployeeDetails.DataSource = DBHelper.FetchEmployeeDetails(cmbBranchesAllEmployees.SelectedValue.ToString(), chkResignedEmployees.Checked, cmbYear.Text);
                if (dgEmployeeDetails.DataSource != null)
                {
                    dgEmployeeDetails.Columns[0].Width = 50;

                    //dgEmployeeDetails.Columns[1].Visible = false;
                    dgEmployeeDetails.Columns[1].Width = 40;
                    dgEmployeeDetails.Columns[1].ReadOnly = true;

                    dgEmployeeDetails.Columns[2].Width = 180;
                    dgEmployeeDetails.Columns[2].ReadOnly = true;

                    dgEmployeeDetails.Columns[3].Width = 120;
                    dgEmployeeDetails.Columns[3].ReadOnly = true;

                    dgEmployeeDetails.Columns[4].Width = 120;
                    dgEmployeeDetails.Columns[4].ReadOnly = true;

                    dgEmployeeDetails.Columns[5].Width = 80;
                    dgEmployeeDetails.Columns[5].ReadOnly = true;

                    dgEmployeeDetails.Columns[6].Width = 80;
                    dgEmployeeDetails.Columns[6].ReadOnly = true;

                    //Added Newly
                    dgEmployeeDetails.Columns[7].Width = 80;
                    dgEmployeeDetails.Columns[7].ReadOnly = true;

                    dgEmployeeDetails.Columns[8].Width = 80;
                    dgEmployeeDetails.Columns[8].ReadOnly = false;
                    dgEmployeeDetails.Columns[8].HeaderText = "Bonus-1";

                    dgEmployeeDetails.Columns[9].Width = 80;
                    dgEmployeeDetails.Columns[9].ReadOnly = false;
                    dgEmployeeDetails.Columns[9].HeaderText = "Bonus-2";

                    dgEmployeeDetails.Columns[10].Width = 80;
                    dgEmployeeDetails.Columns[10].ReadOnly = false;

                    dgEmployeeDetails.Columns[11].Width = 80;
                    dgEmployeeDetails.Columns[11].ReadOnly = true;
                }

                double bonus1 = 0d;
                double bonus2 = 0d;
                double hike = 0d;
                double diff = 0d;

                foreach (DataGridViewRow row in dgEmployeeDetails.Rows)
                {
                    try
                    {
                        bonus1 += double.Parse(row.Cells[8].Value.ToString());
                    }
                    catch (Exception) { }

                    try
                    {
                        bonus2 += double.Parse(row.Cells[9].Value.ToString());
                    }
                    catch (Exception) { }

                    try
                    {
                        hike += double.Parse(row.Cells[10].Value.ToString());
                    }
                    catch (Exception) { }

                    try
                    {
                        diff += double.Parse(row.Cells[11].Value.ToString());
                    }
                    catch (Exception) { }
                }

                lblBonus1Total.Text = bonus1.ToString("c0");
                lblBonus2Total.Text = bonus2.ToString("c0");
                lblHikeTotal.Text = hike.ToString("c0");
                lblDiffTotal.Text = diff.ToString("c0");
                Cursor.Current = Cursors.Default;
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgEmployeeDetails_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                double total = 0d;
                double temp = 0d;

                if (e.ColumnIndex == 7)
                {
                    foreach (DataGridViewRow row in dgEmployeeDetails.Rows)
                    {
                        if (double.TryParse(row.Cells[7].Value.ToString(), out temp))
                        {
                            total += temp;
                        }
                    }
                    lblBonus1Total.Text = total.ToString("c0");
                }
                else if (e.ColumnIndex == 8)
                {
                    foreach (DataGridViewRow row in dgEmployeeDetails.Rows)
                    {
                        if (double.TryParse(row.Cells[8].Value.ToString(), out temp))
                        {
                            total += temp;
                        }
                    }
                    lblBonus2Total.Text = total.ToString("c0");
                }
                else if (e.ColumnIndex == 9)
                {
                    double newSalary = 0d;
                    if (double.TryParse(dgEmployeeDetails[9, e.RowIndex].Value.ToString(), out newSalary))
                    {
                        double oldSalary = double.Parse(dgEmployeeDetails[5, e.RowIndex].Value.ToString());
                        if (oldSalary > newSalary)
                        {
                            MessageBox.Show("Hike should be more than Old Salary", "Invalid Hike", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            dgEmployeeDetails[9, e.RowIndex].Value = oldSalary;
                            dgEmployeeDetails[10, e.RowIndex].Value = "0";
                            return;
                        }
                        dgEmployeeDetails[10, e.RowIndex].Value = newSalary - oldSalary;

                        foreach (DataGridViewRow row in dgEmployeeDetails.Rows)
                        {
                            if (double.TryParse(row.Cells[9].Value.ToString(), out temp))
                            {
                                total += temp;
                            }
                        }
                        lblHikeTotal.Text = total.ToString("c0");

                        total = 0d;
                        foreach (DataGridViewRow row in dgEmployeeDetails.Rows)
                        {
                            if (double.TryParse(row.Cells[10].Value.ToString(), out temp))
                            {
                                total += temp;
                            }
                        }
                        lblDiffTotal.Text = total.ToString("c0");
                    }
                    else
                    {
                        MessageBox.Show("Invalid Value", "Invalid", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        dgEmployeeDetails[9, e.RowIndex].Value = dgEmployeeDetails[3, e.RowIndex].Value;
                        dgEmployeeDetails[10, e.RowIndex].Value = "0";
                        return;
                    }
                }
                else if (e.ColumnIndex == 10)
                {
                    foreach (DataGridViewRow row in dgEmployeeDetails.Rows)
                    {
                        if (double.TryParse(row.Cells[10].Value.ToString(), out temp))
                        {
                            total += temp;
                        }
                    }
                    lblDiffTotal.Text = total.ToString();
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgEmployeeDetails_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.Cancel = false;
        }

        private void btnSaveEmployeeDetails_Click(object sender, EventArgs e)
        {
            try
            {
                if (DialogResult.OK == MessageBox.Show("Do you want to save the details?", "Save", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                {
                    if (DBHelper.SaveBonusHikeDetails(dgEmployeeDetails.Rows, cmbYear.Text))
                    {
                        MessageBox.Show("Saved Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("Some Unknown Error has Occurred", "Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAllEmployeesPrint_Click(object sender, EventArgs e)
        {
            try
            {
                if (DialogResult.OK == MessageBox.Show("Please save data if you are not saved", "Save", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                {
                    PrintActualDGV.Branch = cmbBranchesAllEmployees.Text;
                    PrintActualDGV.Resigned = chkResignedEmployees.Checked;
                    PrintActualDGV.Bonus1Total = lblBonus1Total.Text;
                    PrintActualDGV.Bonus2Total = lblBonus2Total.Text;
                    PrintActualDGV.HikedSalary = lblHikeTotal.Text;
                    PrintActualDGV.Difference = lblDiffTotal.Text;
                    PrintActualDGV.Print_DataGridView(dgEmployeeDetails);
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSyncEmployees_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                if (IsLoggedIn)
                {
                    try
                    {
                        tabControl1.SelectTab(8);
                        if (cmbSyncEmpBranches.DataSource == null)
                        {
                            DataTable dtBranches = DBHelper.FetchBranches();
                            dtBranches.Rows.Add(0, "Central");
                            cmbSyncEmpBranches.DataSource = dtBranches;
                            cmbSyncEmpBranches.DisplayMember = "Branch";
                            cmbSyncEmpBranches.ValueMember = "BranchID";
                            cmbSyncEmpBranches.SelectedIndex = 0;
                        }
                    }
                    catch (Exception)
                    { }
                }
                else
                {
                    tabControl1.SelectTab(5);
                    txtUserName.Focus();
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnGetEmps_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                dgvShowEmployees.DataSource = DBHelper.GetEmployeesByBranch(cmbSyncEmpBranches.SelectedValue.ToString());
                Cursor.Current = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSyncEmpsAtBranch_Click(object sender, EventArgs e)
        {
            try
            {
                if (DialogResult.OK == MessageBox.Show("Do you want to Sync Employees in " + cmbSyncEmpBranches.Text + " Branch?", "Sync Employees", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                {
                    Cursor.Current = Cursors.WaitCursor;
                    if (DBHelper.SyncEmployeesByBranch(cmbSyncEmpBranches.SelectedValue.ToString()) == 0)
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Employees Synced Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        dgvShowEmployees.DataSource = null;
                    }
                    else
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Some Unknown Error has Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    return;
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void cmbPFRequired_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbPFRequired.SelectedIndex == 1)
            {
                txtPFAmt.Clear();
                txtPFAmt.Enabled = false;
            }
            else
            {
                txtPFAmt.Enabled = true;
            }
        }

        private void txtPFAmt_TextChanged(object sender, EventArgs e)
        {
            try
            {
                double value;
                if (!double.TryParse(txtPFAmt.Text, out value))
                    txtPFAmt.Text = string.Empty;
                return;
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnLoanReportPrint_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgEmployeeLoans.DataSource != null)
                {
                    PrintActualDGV.Employee = cmbEmpList.Text;
                    PrintActualDGV.IssuedAmount = dgEmployeeLoans.Rows[0].Cells[1].Value.ToString();
                    PrintActualDGV.IsLoanReport = true;
                    PrintActualDGV.Print_DataGridView(dgLoanCompleteDetails);
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtReduceBillAmt_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                btnPaySalaryData.Enabled = false;

                double billAmt = 0d;
                double.TryParse(BillAmtMain, out billAmt);

                double temp = 0d;
                if (double.TryParse(txtReduceBillAmt.Text, out temp))
                {
                    if (temp > billAmt || temp < 0)
                    {
                        txtReduceBillAmt.Clear();
                        temp = 0;
                    }
                }
                else
                {
                    txtReduceBillAmt.Clear();
                    temp = 0;
                }

                lblBillAmtData.Text = (Math.Round(billAmt - temp, 2)).ToString();
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtReducedAllowanceAmt_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                btnPaySalaryData.Enabled = false;

                double allowanceAmt = 0d;
                double.TryParse(AllowanceAmtMain, out allowanceAmt);

                double temp = 0d;
                if (double.TryParse(txtReducedAllowanceAmt.Text, out temp))
                {
                    if (temp > allowanceAmt || temp < 0)
                    {
                        txtReducedAllowanceAmt.Clear();
                        temp = 0;
                    }
                }
                else
                {
                    txtReducedAllowanceAmt.Clear();
                    temp = 0;
                }

                lblAllowance.Text = Math.Round((allowanceAmt - temp), 2).ToString();
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtLoanAmtData_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                btnPaySalaryData.Enabled = false;

                double loanAmt = 0d;
                double.TryParse(lblBalanceAmtData.Text, out loanAmt);

                double salary = 0d;
                double.TryParse(lblSalaryData.Text, out salary);

                double temp = 0d;
                if (double.TryParse(txtLoanAmtData.Text, out temp))
                {
                    if (temp > loanAmt || temp > salary / 2 || temp < 0)
                    {
                        txtLoanAmtData.Clear();
                        temp = 0;
                    }
                }
                else
                {
                    txtLoanAmtData.Clear();
                    temp = 0;
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtExtraAmount_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                btnPaySalaryData.Enabled = false;

                double temp = 0d;
                if (double.TryParse(txtExtraAmount.Text, out temp))
                {
                    if (temp < 0)
                    {
                        txtExtraAmount.Clear();
                    }
                }
                else
                {
                    txtLoanAmtData.Clear();
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCalculate_Click(object sender, EventArgs e)
        {
            CalculateLatest();
            btnPaySalaryData.Enabled = true;
        }

        #region Hike Salary

        private void btnSalaryHike_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    dgvHikeSalary.DataSource = null;
                    tabControl1.SelectTab(9);
                    btnHikeSalaryNow.Enabled = false;
                }
                catch (Exception ex)
                {
                    WriteToEventViewer(ex.Message);
                    MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabControl1.SelectTab(5);
                txtUserName.Focus();
            }
        }

        private void btnSearchEmpHikeSalary_Click(object sender, EventArgs e)
        {
            try
            {
                dgvHikeSalary.DataSource = null;
                btnHikeSalaryNow.Enabled = false;

                DataTable dt = new DataTable();
                dt.Columns.Add("EmpID");
                dt.Columns.Add("EmpName");

                if (Employees == null)
                    Employees = DBHelper.FetchEmployeesByName(txtNameSearch.Text.Trim(), true);

                cmbEmpHikeSalary.DataSource = null;

                foreach (DataRow row in Employees.Rows)
                {
                    if (txtEmpHikeSalary.Text.Trim() != string.Empty)
                    {
                        if (!(row["EmpName"].ToString().StartsWith(txtEmpHikeSalary.Text.Trim()) || row["EmpName"].ToString().ToUpper().StartsWith(txtEmpHikeSalary.Text.Trim().ToUpper()) || row["EmpID"].ToString().StartsWith(txtEmpHikeSalary.Text.Trim())))
                        {
                            continue;
                        }
                    }
                    DataRow dr = dt.NewRow();
                    dr[0] = row["EmpID"].ToString();
                    dr[1] = row["EmpID"].ToString() + " - " + row["EmpName"].ToString() + " - " + row["Department"].ToString() + " - " + row["Branch"].ToString();
                    dt.Rows.Add(dr);
                }
                cmbEmpHikeSalary.DataSource = dt;
                cmbEmpHikeSalary.ValueMember = "EmpID";
                cmbEmpHikeSalary.DisplayMember = "EmpName";
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnFetchHikes_Click(object sender, EventArgs e)
        {
            try
            {
                btnHikeSalaryNow.Enabled = false;
                lblEmp.Text = cmbEmpHikeSalary.SelectedValue.ToString();
                txtNewSalary.Clear();
                DataSet dsDetails = DBHelper.GetHikeByEmpID(cmbEmpHikeSalary.SelectedValue.ToString());
                if (dsDetails != null && dsDetails.Tables.Count == 2)
                {
                    dgvHikeSalary.DataSource = dsDetails.Tables[0];
                    dgvHikeSalary.Columns[1].Visible = false;
                    lblOldSalary.Text = dsDetails.Tables[1].Rows[0]["Salary"].ToString();
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtNewSalary_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                btnHikeSalaryNow.Enabled = false;
                double newSalary = 0d;
                if (double.TryParse(txtNewSalary.Text, out newSalary) && newSalary > 0)
                {
                    //double oldSalary = 0d;
                    //double.TryParse(lblOldSalary.Text, out oldSalary);

                    //if (newSalary > oldSalary)
                    //{
                    btnHikeSalaryNow.Enabled = true;
                    //}
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnHikeSalaryNow_Click(object sender, EventArgs e)
        {
            try
            {
                if (DBHelper.HikeSalary(lblEmp.Text, lblOldSalary.Text, txtNewSalary.Text) > 0)
                {
                    MessageBox.Show("Salary Modified Successfully", "Modify Salary", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    btnFetchHikes_Click(sender, e);
                }
                else
                {
                    MessageBox.Show("Some unknown error has occurred.", "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion
    }

    public enum UserActionType
    {
        PaySalaryClick,
        PayAdvanceClick,
        PayOTClick,
        PayBillClick,
        PayLeaveClick,
        AdvanceToLoan
    }

    public enum LeaveOrOT
    {
        Leave = 1,
        OT = 2
    }

    public enum AdvanceOrBill
    {
        Advance = 1,
        Bill = 2
    }
}